Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React: How to get data from Axios, not Promise?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please help. I appreciate it!

>Solution :

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>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading