Unable to update useState with array of objects

Viewed 38
 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

1 Answers

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.

Related