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

120
Visualizações
React multiple state changes with delay

I'm trying to add multiple items to a list where each item is added after some delay, but when I use the setState it either seems to not change the state or it doesn't re-render the components, I would like to know why this happens.

import React, { useState } from 'react';
import './App.css';

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};

function App() {
    const [messages, setMessages] = useState([]);

    const createMessages = async () => {
        for (let i = 0; i < 10; ++i) {
            console.log("test");
            setMessages([...messages, "test"]);
            await sleep(1000);
        }
    };

    return (
        <div id="App">
            <button onClick={createMessages}>Create Messages</button>
            <div>
                {messages.map((message, index) => <p key={index}>{message}</p>)}
            </div>
        </div>
    );
}

export default App;

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use the callback inside setState to set your messages. Right now you are calling createMessages and there is an empty array in the messages and that is the value your function is using. So the reason you are only seeing one item in the array is because every time you set the state there is an empty array then you add the test to the array and the component re renders and only shows the one test. So do like this when you set your state:

setMessages(prevMessages => [...prevMessages, "test"]);

Now you will use the correct value when setting your state.

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