Home > Blockchain >  React multiple state changes with delay
React multiple state changes with delay

Time:11-06

I'm trying to add multiple items to a list where each item is added after some delay, but when I use the setState it either seems to not change the state or it doesn't re-render the components, I would like to know why this happens.

import React, { useState } from 'react';
import './App.css';

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};

function App() {
    const [messages, setMessages] = useState([]);

    const createMessages = async () => {
        for (let i = 0; i < 10;   i) {
            console.log("test");
            setMessages([...messages, "test"]);
            await sleep(1000);
        }
    };

    return (
        <div id="App">
            <button onClick={createMessages}>Create Messages</button>
            <div>
                {messages.map((message, index) => <p key={index}>{message}</p>)}
            </div>
        </div>
    );
}

export default App;

enter image description here

CodePudding user response:

Use the callback inside setState to set your messages. Right now you are calling createMessages and there is an empty array in the messages and that is the value your function is using. So the reason you are only seeing one item in the array is because every time you set the state there is an empty array then you add the test to the array and the component re renders and only shows the one test. So do like this when you set your state:

setMessages(prevMessages => [...prevMessages, "test"]);

Now you will use the correct value when setting your state.

  • Related