Is there another way to get data from an API endpoint or resolve this returned data?

Advertisements

I am trying to fetch data from an endpoint in my project, but continue to get a Promise back instead of the actual data. First of all I should say that I am not getting an error, however I just don’t understand why I couldn’t handle the returned data from the api call outside of the function.

So I have this function fetchUser that makes a call to the API, and returned the data successfully when I log it to the console. But what I want is to be able to use this data in my JSX. Below is the function call to the API route:

 const fetchUser = async () => {
    const baseUrl = "/api/user";
    const response = await axios.get(baseUrl);
    const { data } = response;

    const role = data.map((item) => {
      const { role } = item;
      return role;
    });
    return role;
  };

  const userRole = fetchUser().then((result) => {
    console.log(result) // returned the data as I expected and wanted (e.g: [Brand])
    return result;
  });

  console.log("Role", userRole); // Returned a 'Promise'(as shown below)

Role:
Promise {<pending>}
[[Prototype]]
Promise
[[PromiseState]]
"fulfilled"
[[PromiseResult]]
Array(1)

Please point me in the right direction to resolve this issue

>Solution :

This happens because of the async nature of the Promise object. What you’re storing in the userRole variable is a Promise object.

One way to work this out is either await the response, like this:

// This is my preferable method, as I can avoid nested calls
try {
  const userRole = await fetchUser();
  console.log(userRole)
}
catch (error) {
  console.log(error)
}

The other way is to handle your data inside the .then(), like this:

fetchUser()
  .then(res => console.log(res))
  .catch(error => console.log(error))

Leave a ReplyCancel reply