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

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

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 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