0

I want to immutable remove an object entry in react reducer

obj = {
   selections: {}
}

this is how i add things to my selections obj

return {
  ...state,
  selections: {
    ...state.selections,
    [action.data.type]: action.data
  }
};

this will give me

selections: {
    test: { some funky data } 
}

then when i want to remove test? How do i accomplish that?

0

Maybe something like this,

this.setState(state => {
   return {
     ...state,
     selections: {
        ...state.selections,
        selections: delete state.selections.test
     }
   }
})
  • This will just alter selections to true – heathrow Jun 12 at 12:01
0

The best i could do for now is to set it to null

return {
  ...state,
  selections: {
    ...state.selections,
    [action.data.type]: null
  }
};

its not firing the update when i use Object.assign and using delete

0

Just copy your state to a temporal variable, then delete the that you don't want:

//...
case 'REMOVE_PROPERTY':
  //here we make a copy of selection object, note that this is a shallow copy
  let newSelections = { ...state.selection };
  delete newSelections[action.data.type];
  return {
    ...state,
    //here we overwrite selections object on a new created object before returning the value
    selections: newSelections
};
//...
  • This will not indicate for react to re-render. It doesnt think its changed – heathrow Jun 13 at 5:45
  • I'm using this pattern in an app and works as expected, how is your component connected? – ramirozap Jun 13 at 7:46
  • export connect( state => ({ selections: state.selections }), dispatch => ({ }) )(Class)); – heathrow Jun 13 at 12:00
  • here it is a working version, take a look: codesandbox.io/s/determined-cannon-3en8v?fontsize=14 – ramirozap Jun 13 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.