Purohit Iyer
Purohit Iyer

Reputation: 53

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?

Upvotes: 2

Views: 13626

Answers (5)

Rahul Kumar
Rahul Kumar

Reputation: 3157

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();

Upvotes: 1

Dostonbek Oripjonov
Dostonbek Oripjonov

Reputation: 1674

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

Upvotes: 1

amir najafi
amir najafi

Reputation: 54

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

  })


Upvotes: 2

ATK
ATK

Reputation: 368

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

Upvotes: 3

Viet
Viet

Reputation: 12777

You can use async/await to get data:

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

Upvotes: 1

Related Questions