Home > Blockchain >  State not updating on removing value from array in React JSX funcntional component
State not updating on removing value from array in React JSX funcntional component

Time:01-03

Values are adding into array by checkbox selection which is working fine and updating state but when i am doing for removing value from array state is not udpating but array is getting modified

Array

  const [selectedKeys, setSelectedKeys] = React.useState([]);

event

 if (event.target.checked) {
               //adding values to array
      setSelectedKeys([...selectedKeys, event.target.value]);
    } else {
      var index = selectedKeys.indexOf(event.target.value);
      if (index >= -1) {
             //Removing values from array
        selectedKeys.splice(index, 1);
      }
      setSelectedKeys(selectedKeys);
    }

CodePudding user response:

The splice method just mutates the existing array instance and React avoids rerendering the array thinking it's the same array (React uses referential equality). You need to create a new array after removing the item.

Any of the following would work

Using spread operator to create a new array.

if (event.target.checked) {
    //adding values to array
    setSelectedKeys([...selectedKeys, event.target.value]);
} else {
    var index = selectedKeys.indexOf(event.target.value);
    if (index >= -1) {
        //Removing values from array
        selectedKeys.splice(index, 1);
    }
    setSelectedKeys([...selectedKeys]);
}

Filter the array which also outputs a new array

if (event.target.checked) {
    //adding values to array
    setSelectedKeys([...selectedKeys, event.target.value]);
} else {
    var index = selectedKeys.indexOf(event.target.value);
    if (index >= -1) {
        //Removing values from array and set the new array
        setSelectedKeys(
            selectedKeys.filter((item, itemIndex) => itemIndex !== index)
        );
    }
}
  • Related