Remove item from Redux state

I am wondering if you can help me with this problem, if possible. I am trying to remove an item from Redux state. I went through the identifier of the element that the user clicks through action.data in the reducer.

I am wondering how can I map action.data to one of the IDs in Redux state and then remove this object from the array? I also wonder how it is best to set a new state after deleting a single object?

See 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 || []; } } 
+6
source share
1 answer

Just filter the comments:

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

This way you will not mutate the original state array, but return a new array without an element that had the commentId identifier.

To be more concise:

 case 'DELETE_COMMENT': return state.filter(({ id }) => id !== action.data); 
+41
source

All Articles