0

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 ?

3
  • Actually there isn't a problem with your code. It's just that when you log selectedItems the state isn't updated yet. Commented Mar 6, 2020 at 10:18
  • setSelectedItems is asynchronous, it will not update state immediately. You are getting stale state. Commented Mar 6, 2020 at 10:19
  • @hussain.codes , so what are instruction added, to have the current state of the array Commented Mar 6, 2020 at 10:24

2 Answers 2

3

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])
Sign up to request clarification or add additional context in comments.

1 Comment

when I try useEffect and i log(selectedItems) I have the latest index added in the array not list of indexes, the problem that the concatenation of indexes does not do this correctly
0

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

2 Comments

when i do this change montioned in my function , this is the result after adding 3 new indexes, newSelectedItems [1] index 1 newSelectedItems [2] index 2 newSelectedItems [3] index 3 the expected result => newSelectedItems[1,2,3] index 3 . it's like setSelectedItems() doesn't work, it doesn't update the array, it always keeps the initial state of the array
Can you post your entire component? I just tested it and it works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.