I'm facing a really strange bug which i have never seen before.
I fetch the data from server and i get an array of objects then I'm trying to setState with fetched data but my state is empty! Help someone please.
Asked
Active
Viewed 35 times
-1

skyboyer
- 22,209
- 7
- 57
- 64
-
1It would be preferable if you posted your code as text, not in image form(See [mcve]). – SuperStormer Mar 29 '20 at 21:38
-
setState is async, so the effects won't be seen immediately. – SuperStormer Mar 29 '20 at 21:39
2 Answers
0
Updating state in React is not a sync operation. It's async for optimization (to group changes together and change state only once).
You can use useEffect
to react on changes:
useEffect(() => { console.log(state)}, [state])
or you can just show your state
inside of return
(return
calls every time when component re-renders, component rerenders because of useState
calls).

Max Starling
- 967
- 8
- 8
0
Updating state in react is an asynchronous operation. You should instead log out data in a useEffect.
useEffect(() => {
console.log(state)
}, [state]);

Justin Boyle
- 32
- 4