Search code examples
javascriptreactjssettimeout

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

Solution

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