Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
        );
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading