Fetching data in React's useEffect() returns "undefined"
14,374
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
Author by
Nittoc
Updated on June 04, 2022Comments
-
Nittoc almost 2 years
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"
-
crashmstr over 4 years
accountInfos
is set asynchronously, so you cannot expect it to be set until later (outside the scope of where youawait
the data being fetched). Your code needs to test if the data exists yet or not. -
Titus over 4 yearsYou've misunderstood how
useState
works, once you call aset..
function, your functional component will be re-executed and only then that state value will have the new value.
-
-
Nittoc over 4 yearsBut still tried your suggestion. First it also returns "undefined" then it returns teh correct object. So it fires two times
-
Nittoc over 4 yearsBut I dont really now what to do with this Information.
-
Astrit Spanca over 4 yearsThe data you get from that fetch you will probably display somewhere inside JSX which is placed inside return(); So you will face no issues there. As for your case i think Daniel Herrero Hernando gave you the right answer.
-
DanCouper about 4 yearsThe question is literally about fetching data in
useEffect
, it's in the question title and the code is in the question body. Is this an answer to a different question (your answer doesn't seem to relate to anything here)?