Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda