Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!