Mojackoo
Mojackoo

Reputation: 93

ReactJs UseState : insert element into array not updating

I am trying to use React Hooks but somehow my state is not updating. When I click on the checkbox (see in the example), I want the index of the latter to be added to the array selectedItems, and vice versa

My function looks like this:

const [selectedItems, setSelectedItems] = useState([]);

const handleSelectMultiple = index => {
    if (selectedItems.includes(index)) {
        setSelectedItems(selectedItems.filter(id => id !== index));
    } else {
        setSelectedItems(selectedItems => [...selectedItems, index]);
    }
    console.log("selectedItems", selectedItems, "index", index);
};

You can find the console.log result here

An empty array in the result, can someone explain to me where I missed something ?

Upvotes: 0

Views: 494

Answers (2)

Harmenx
Harmenx

Reputation: 946

Because useState is asynchronous - you wont see an immediate update after calling it.

Try adding a useEffect which uses a dependency array to check when values have been updated.

useEffect(() => {
    console.log(selectedItems);
}, [selectedItems])

Upvotes: 3

Omar
Omar

Reputation: 16623

Actually there isn't a problem with your code. It's just that when you log selectedItems the state isn't updated yet.

If you need selectedItems exactly after you update the state in your function you can do as follow:

const handleSelectMultiple = index => {
    let newSelectedItems;
    if (selectedItems.includes(index)) {
        newSelectedItems = selectedItems.filter(id => id !== index);
    } else {
        newSelectedItems = [...selectedItems, index];
    }
    setSelectedItems(newSelectedItems);
    console.log("selectedItems", newSelectedItems, "index", index);
};

Upvotes: 0

Related Questions