0
 const [myPhotos, setMyPhotos] = useState([]);

  let token = localStorage.getItem('token');

  const axiosConfig = {
    headers: {
      "Content-type": "application/json",
      "responseType": "json",
      "Authorization": token
    },
  };

  useEffect(() => {
   axios.get('http://localhost:5050/mypost', axiosConfig)
  .then((res) => {
    console.log(res.data)
    setMyPhotos(res.data)
    console.log(myPhotos)
  })
   .catch((e) => {
      console.log(e)
    });
  }, []);

I am getting array of objects in res.data but myPhotos is not updating after setMyPhotos(res.data) . Can anyone please help me?

Display of Developer console in Google Chrome

Rwitesh Bera
  • 389
  • 2
  • 3
  • 9
  • setMyPhotos(res.data) won't update the state immediately, rather react will batch the updates. Move the console.log(myPhotos) and changes will be reflected – Mridul Gupta Aug 28 '22 at 10:11
  • Does this answer your question? [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) – Sergey Sosunov Aug 28 '22 at 10:14

1 Answers1

2

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.

Which is why we have useEffect, a built-in React hook that activates a callback when one of it's dependencies have changed.

Example:

useEffect(() => {
   console.log(myPhotos)
   // Whatever else we want to do after the state has been updated.
}, [myPhotos])

This console.log will run only after the state has finished changing and a render has occurred.

  • Note: "myPhotos" in the example is interchangeable with whatever other state piece you're dealing with.

Check the documentation for more info about this.

tomleb
  • 2,409
  • 2
  • 9
  • 24