Bradley Bradley - 3 months ago 54
React JSX Question

Delete an item from Redux state

I'm wondering if you could help me with this problem if possible. I am trying to delete an item from the Redux state. I have passed in the ID of the item that the user clicks via

action.data
into the reducer.

I'm wondering how I can match the
action.data
with one of the ID's within the Redux state and then remove that object from the array? I am also wondering the best way to then set the new state after the individual object has been removed?

Please see the code below:

export const commentList = (state, action) => {
switch (action.type) {
case 'ADD_COMMENT':
let newComment = { comment: action.data, id: +new Date };
return state.concat([newComment]);
case 'DELETE_COMMENT':
let commentId = action.data;

default:
return state || [];
}
}

Answer

Just filter the comments:

case 'DELETE_COMMENT':
  const commentId = action.data;
  return state.filter(comment => comment.id !== commentId);

This way you won't mutate the original state array, but return a new array without the element, which had the id commentId.

Comments