Home > Mobile >  How do I remove an element from a state using useState?
How do I remove an element from a state using useState?

Time:10-14

I'm generating a list of values from checkboxes.

const [checkedState, setCheckedState] = useState({});

const handleOnChange = (e) => {
  if(e.target.checked === true){
    setCheckedState({ ...checkedState, [e.target.name]: e.target.checked });
  } else {
    setCheckedState({...checkedState, [e.target.name]: e.target.checked.filter(element => element !== e.target.checked)})
  }    
};

When I console log it, I get this checkedState: {action/adventure: true, documentary: true}, etc. when I check the boxes. Which is fine! But likewise, I need to remove it from that object, when I uncheck it. So the else portion is my problem.

Realistically, if I unchecked documentary, I should console.log checkedState: {action/adventure: true}

CodePudding user response:

const handleOnChange = (e) => {
  if(e.target.checked === true){
    setCheckedState({ ...checkedState, [e.target.name]: e.target.checked });
  } else {
    const copyOfCheckedState = {...checkedState};
    delete copyOfCheckedState[e.target.name];
    setCheckedState(copyOfCheckedState);    
};

Alternative using rest in destructuring assignment. It's a bit harder to grasp when you are not used to the syntax, so I wouldn't advice:

 } else {
    const {[e.target.name]: _targetName, ...checkedStateWithoutTargetName} = checkedState;
    setCheckedState(checkedStateWithoutTargetName);    
};

Note

As @sasi k pointed out it's recommended to use the callback form of setState when you depend of the previous state, so you'd rather do something like

setCheckedState(checkedState => {
  // return new state
});

CodePudding user response:

Use delete to remove property from object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

Ideally if you are updating state using previous state you should do this

const handleOnChange = (e) => {
  if (e.target.checked === true) {
     setCheckedState(prevState => ({
       ...prevState,
       [e.target.name]: e.target.checked
     }));
  } else {
      setCheckedState((prevState) => {
         delete prevState[e.target.name];
         return prevState
      })
   }
};

Refer React official docs for more info https://reactjs.org/docs/hooks-reference.html#functional-updates

  • Related