Home > Software design >  How to Delete an Object from state in react?
How to Delete an Object from state in react?

Time:10-14

I have this object that I want to delete according to id. the classic delete object doesn't seem to be working I am copying the state calling the delete but it is giving me an error is it my syntax or should the delete be handled differently ?

// State Object Model
Items : {
id1 : [some items ],
id2 : [some items ],
id3 : [some items ],
id4 : [some items ],
id4 : [some items ],
}
// Reducer Delete Logic
 case DELETE_OBJ:    
return {
  Items: {
    ...state.Items,
    delete Items[id1]
    }
  };

CodePudding user response:

Shallow copy first, then delete. You necessarily need to shallow copy all state, and nested state, that you are updating. In this case you shallow copy the root state and then also the nested Items state object.

// Reducer Delete Logic
case DELETE_OBJ:    
  const newState = {
    ...state,
    Items: {
      ...state.Items,
    },
  }
  delete newState.Items[id1];
  return newState;
};
  • Related