Home > Back-end >  Settimout use old data
Settimout use old data

Time:12-06

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'}]);
}

CodePudding user response:

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;
});
}

CodePudding user response:

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.

  • Related