Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios get function returns a promise in React

I tried fetching data from a giphy api using the following function and print the returned value to the browser console.

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

  const data = fetchData(giphy_url);
  console.log(`Data: ${data}`);

But on printing the value of the data variable, it prints:

Data: [object Promise]

I want the data in the response to be accessed. Is there something that I am missing?

like image 540
Purohit Iyer Avatar asked Apr 12 '26 11:04

Purohit Iyer


1 Answers

Axios API calls return a Promise object. From Axios documentation, "Axios is a promise-based HTTP Client for node.js and the browser."

You would need to await on a promise object to access the response value. Note that in order to use await keyword in your function, you would need to mark it as async. Do something like below.

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

  const data = fetchData(giphy_url);
  console.log(`Data: ${data}`);
like image 101
Lambda Avatar answered Apr 15 '26 00:04

Lambda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!