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

150
Visualizações
Why does react have old state data after await

I am trying to update an array in of data that is loaded async from an API (e.g. the user clicks on an item, and it requests the data, and adds it to the list to be displayed a few seconds later.)

I understand that state is not updated immediately, but that is not what is happening, the state has updated, but the code after await still sees the old state.

I can see items has been updated because the useEffect fires and outputs the updated array, but then after that, when the await has finished, the async code sees items in its original state.

  const [items, setItems] = useState([]);

  useEffect(() => {
    console.log(`${items.length} items`);
  }, [items]);

  const addItemFromAPI = async () => {
    const name = await getNextItemFromAPI();
    // Why is items still referencing the previous copy from BEFORE await?
    console.log(`${items.length} existing items`);
    setItems([...items, { name }]);
  };

Am I doing this completely wrong, is there a pattern for async appending of data to state?

If I change it to useRef() and then use .current.push() it works as expected, which leads me to believe something weird is happening with useState.

https://codesandbox.io/embed/angry-worker-mczcsv?fontsize=14&hidenavigation=1&theme=dark

almost 4 years ago · Santiago Trujillo
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