0

hope you guys have a great great day! :)

I want to ask something, i need to return some list data from API,

I have 3 files, one called getUser.js and the othe is User.js and OtherUser.js, i already fetch the data from API in getUser.js, and i need to access the data from getUser.js to populate User.js and OtherUser.js

The Problem is, i can't return the data in getUser.js

here's my code in getUser.js

import React from "react";

export const getUser = async () => {
  await fetch("https://myapi.com")
    .then((response) => response.json())
    .then((res) => {
      return res;
    });
};

and when i console.log inside User.js and OtherUser.js, i got this

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

the log

and here's my code in User.js and OtherUser.js looks like:

import React, {useState} from 'react'
import { getUser } from './someplace/getUser'

export default function User() {
  useEffect(()=>{getDataFromUser()},[])

  const getDataFromUser = async() => {
   console.log(getUser())
  }
}

Did you guys know why? please help :)

1
  • You have to await getUser() Commented Jun 28, 2022 at 6:40

2 Answers 2

2

Avoid using then chains, when using async-await. Refactor your getUser funciton to

export const getUser = async () => {
  const response = await fetch("https://myapi.com");
  const json = await response.json();
  return json;
};

Then in your User component

console.log(await getUser())
Sign up to request clarification or add additional context in comments.

2 Comments

Thanksss brotherr!!
above is the correct answer :)
1

You are logging a Promise, that's why you're seeing this in your console.

When inside async function, if you want to get the result of the function, you should not use "then".

So you could do something like this:

const getUser = async () => {
  let response = await fetch("https://httpbin.org/get");
  return await response.json();
};

But, notice that if fetch fails, it may throw an exception. So I recommend using a try/catch block

Also notice that in this case, when you call getUser(), you will have to use "await" before calling the function to get the json response. For example:

let user = await getUser();

In case you want to run a async function inside the useEffect hook, try doing something like this:

React.useEffect(()=>{
  onOpen = async () => {            
    console.log(await getUser());
  }
  onOpen();
},[]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.