0

I am trying to write a function that removes all the elements from an array called selectedItems.

It looks like this:

  const selectNone = (e: any) => {

    let selectedItemsCopy = selectedItems;
    selectedItemsCopy = []

    setState(
      {
        ...state,
        areAllSelected: false,
        isChecked: false,
        selectedItems: selectedItemsCopy
      }
    );
  }

but in setState, selectedItems does not get updated to the empty copy of the array. What am I doing wrong?

1 Answer 1

2

The problem that you have is, that you are actually mutating state, which is basically prohibited in React. In this case, it's very simple to solve, just put the [] inside the setState directly, without any variables:

  const selectNone = (e: any) => {
    setState(
      {
        ...state,
        areAllSelected: false,
        isChecked: false,
        selectedItems: []
      }
    );
  }

The method you are using to make a copy of the array, doesn't actually copy the array and instead just creates a reference to the original (that's how JS works). In order to make a proper copy (for example to be able to make modifications, not just clear the array), you should use Array.from().

Here's an example

  const selectNone = (e: any) => {

    let selectedItemsCopy = Array.from(selectedItems);
    selectedItemsCopy[x] = changedValue;

    setState(
      {
        ...state,
        areAllSelected: false,
        isChecked: false,
        selectedItems: selectedItemsCopy
      }
    );
  }
Sign up to request clarification or add additional context in comments.

2 Comments

the [] is what I had initially, which also didn't work!
@helloWorld There must be a mistake somewhere else in your component then, could you provide more of the component?

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.