Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
React, state not getting updated when calling the related setState

I am trying to fetch images from an Unsplash API, and then trying to update the images data using useState in the following code.

const [images, setImages] = useState([]);

  useEffect(() => {
    Axios.get(
      "https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
    )
      .then((res) => {
        //res.data is printing correct/expected value
        console.log(res.data);

        setImages(res.data);
        console.log("lul");

        //but images array is still empty
        console.log("images: ", [images]); // []
      })
      .catch((err) => console.error(err));
  }, []);

If I put the images array in the dependency array, then I am able to update the image array, but then fetching is occurring infinitely.

Why this is happening?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

What you are doing wrong is that your are trying to console.log before React has re-rendered. Updating a state through the related setState is not instantaneous, it's an asynchronous task. A re-render is needed to get the updated value. See the code below, I added comments.

Also it's a bad idea to put images in the dependencies' array, you will get an infinite loop.

const [images, setImages] = useState([]);
 
console.log("images: ", [images]); // you get [] for the first time, and after state change and re-render, it will contains the fetched data.

useEffect(() => {
  Axios.get(
    "https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
    )
    .then((res) => {
      setImages(res.data);
    })
    .catch((err) => console.error(err));
}, []);
about 4 years ago · Juan Pablo Isaza Report

0

setState is invoked asynchronous (though is doesn't return a promise so you can't await it).

Keep your useEffect as it is now, and in order to print the new value whenever the images changes, you can use another useEffect:

  useEffect(() => {
    console.log("images: ", [images]); // []
  }, [images]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!