-1

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. enter image description here

skyboyer
  • 22,209
  • 7
  • 57
  • 64

2 Answers2

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]);