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

171
Vistas
Settimout use old data

I have an array of message messages from a bot and a user. First, the add Bot Message function is triggered, where a message from the user is first added, and then from the bot after 2 seconds.

What is the problem: The message from the user (the addUserMessage function) works fine, but after 2 seconds it adds a message from the bot, but at the same time deletes the user's message.

I understand that setTimeout uses the old data of the message array and rewrites the message from the user

How to fix it? Thanks

const [messages, addMessages]=useState([]);

const addBotMessage=async (value, callback)=>{
  addUserMessage(value, callback);
  setTimeout(()=>{
    addMessages([...messages,{content:BotContent[callback], time:getTime(), author:'bot'}]);
  },2000)
}

const addUserMessage=(value, callback)=>{
 if(!value) return;
 addMessages([...messages,{content:value, time:getTime(), author:'user'}]);
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try this:

const [messages, addMessages]=useState([]);

const addBotMessage=async (value, callback)=>{
    addUserMessage(value, callback);
    setTimeout(()=>{
        addMessages(prevMessages => {
            const nextMessages = [...prevMessages];
            nextMessages.push({content:BotContent[callback], time:getTime(), author:'bot'});
            return nextMessages;
        });
    },2000)
}

const addUserMessage=(value, callback)=>{
if(!value) return;
addMessages(prevMessages => {
    const nextMessages = [...prevMessages];
    nextMessages.push({content:value, time:getTime(), author:'user'});
    return nextMessages;
});
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

If the only reason ist to have some delay between those messages i'd do it in another way:

addUserMessage(value, callback);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessages([...messages,{content:BotContent[callback], time:getTime(), author:'bot'}]);

That way you would just delay the addition of the second command while working on the right current 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