5ecured
5ecured

Reputation: 201

Why is axios returning a promise?

I have this

import axios from 'axios'

export const fetchData = async () => {
    const URL = 'url here'
    const { data } = await axios.get(URL)
    return data
}

At this point, I get the data I want, an array of objects

Array(6) [ {…}, {…}, {…}, {…}, {…}, {…} ]

Yet in another file when I use the fetchData function:

const DisplayPeople = () => {
    const data = fetchData()
    console.log(data);
    return (
        <div>DisplayPeople</div>
    )
}

Here, what I get is instead:

Promise { <state>: "pending" }
   <state>: "fulfilled"
   <value>: Array(6) [ {…}, {…}, {…}, … ]
   <prototype>: Promise.prototype { … }

Why is it like this? I just want to get the same result as I get in the fetchData function

Upvotes: 1

Views: 88

Answers (1)

Nicholas Carey
Nicholas Carey

Reputation: 74187

You get a promise return in the second case

const DisplayPeople = () => {
  const data = fetchData()
  console.log(data);
  return (
    <div>DisplayPeople</div>
  )
}

because your fetchData() is an async function. And all async functions return a promise, even something like

async function get5() {
  return 5;
}

So unless you await fetchData(), you'll get a promise instead of the value of the settled promise that it returns.

Upvotes: 1

Related Questions