Home > Software design >  React: How to get data from Axios, not Promise?
React: How to get data from Axios, not Promise?

Time:01-09

I'm trying to get data from a link but all I get is a Promise. Here is my example code:

import axios from "axios";

export default function App() {
  const url = `https://finnhub.io/api/v1/stock/profile2?symbol=GME&token=c6a500qad3idi8g5o2v0`;

  const fetchData = async (u) => {
    return await axios.get(u).then((res) => res.data);
  };

  return (
    <div className="App">
      <button onClick={() => console.log(fetchData(url))}>click me</button>
    </div>
  );
}

I don't know which part of the code is wrong that it keeps giving out the Promise like the photo here:

enter image description here

Please help. I appreciate it!

CodePudding user response:

You can do it like this

  import axios from "axios";

export default function App() {
  const url = `https://finnhub.io/api/v1/stock/profile2?symbol=GME&token=c6a500qad3idi8g5o2v0`;
  const [data, setData] = React.useState(null);
  const fetchData = async (u) => {
    return await axios.get(u).then((res) => {
      setData(res.data);
      console.log(res.data.name);
    });
  };

  return (
    <div className="App">
      <button onClick={() => fetchData(url)}>click me</button>
      Name :{data?.name}
    </div>
  );
}
  •  Tags:  
  • Related