Fetching data in React's useEffect() returns "undefined"

Nittoc picture Nittoc · Nov 19, 2019 · Viewed 7.3k times · Source

I'm trying to fetch data from a database. It's a get request. All works fine as long I am using the fetched data in the async function. But ouside of it, it just returns "undefined". What am I doing wrong? Thanks for your help :)

const [accountInfos, setAccountInfos] = useState();
      const [error, setError] = useState();
      const [loading, setLoading] = useState(true);

      useEffect(() => {
        (async function runEffect() {
            const fetchedAccountInfos =  await fetchAccountInfos();
            if (fetchedAccountInfos && fetchedAccountInfos.length > 0) {
                console.log(fetchedAccountInfos)  //This console.log works
                setAccountInfos(fetchedAccountInfos);
                setLoading(false);
                console.log(accountInfos)  //This console.log returns 
                                             "undefined"
              } else {
                setError("Accountdaten können nicht geladen werden!");
                setLoading(false);
                };
        })();
      }, []);
      console.log(accountInfos);  //This console.log returns "undefined"

Answer

DanCouper picture DanCouper · Nov 19, 2019

It's not React-specific: that's an async function, so the promise is going to resolve after the console log occurs, that's why you get undefined. This is just normal JS behaviour -- the value is undefined at the point console.log executes.

In the return value where you define the JSX, render null (or some empty state component) if accountinfos is null, otherwise render the actual component based on the return value from the API. Once you get a response, the state will update and the component will rerender