Axios get function returns a promise in React

Viewed 4005

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?

5 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}`);

It happend because javascript is a non blocking language and axios' get function is a promise function. So when you print your data variable which is not fill yet, you should use it like this.

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

// careful that when you want to use await it should be on async function
  const data = await fetchData(giphy_url);
  console.log(`Data: ${data}`);

  // or 
  fetchData(giphy_url).then((data)=>{
    console.log(`Data: ${data}`);

  })


You can use async/await to get data:

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

I think you are handling axios in wrong way

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

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

Use async-await concept as below:

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

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

getData();
Related