Fetching data in React's useEffect() returns “undefined”

 ̄綄美尐妖づ 提交于 2021-01-27 18:38:58

问题


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"

回答1:


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




回答2:


You are not doing anything wrong, the console.log outside the useEffect just executes once, on the initial component function call, so at that time the accountInfos variable is still undefined.

However, the console.log inside the useEffect is executed after fetching the data so it is defined at that time.




回答3:


Try this just to see the result?

      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) {
                setAccountInfos(fetchedAccountInfos);
                setLoading(false);
                console.log(accountInfos)  //This console.log works
              } else {
                setError("Accountdaten können nicht geladen werden!");
                setLoading(false);
                };
        })();
      }, []);
      console.log(accountInfos);  //This console.log returns "undefined"

      useEffect(() => {
        console.log(accountInfos); //check the result here
      }, [accountInfos])



回答4:


In order to get the updated value and then do some action based on that value, you need to use a useEffect hook

e.g.

const [toggle, setToggle] = useState(false);

useEffect(() => {
   // do something based on new value of toggle
}, [toggle]);

const trigger = () => {
  setToggle(true);
  // OR
  //setToggle(t => !t);
}


来源:https://stackoverflow.com/questions/58934643/fetching-data-in-reacts-useeffect-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!