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

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

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

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