Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda