Search code examples
objectreduxstatestorelodash

Deleting Object in Redux State with Id in Lodash/Javascript


I'm referring to this solution on removing an unwanted ID from a redux state. My state is set up slightly differently and I'm not sure how to use lodash to filter it.

My array:

[
  {id:1, animal:fish, name:bob}, 
  {id:2, animal:dig,name:jim}, 
  {id:3,animal:cat, name:Tk} 
]

This is my offending code (I'm passing the ID as the action.payload):

const INITIAL_STATE = { animals:[]};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case DELETE_ANIMAL:
        let animalId = action.data;
        return {...state, animals: [...state.filter(c => c.id !== animalId)]; 
  }
  return state;
}

Solution

  • I don't think you need to use lodash for this. Just filter the animals array:

    case DELETE_ANIMAL:
            let animalId = action.data;
            return {...state, animals: state.animals.filter(c => c.id !== animalId)}