Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  129] [ 5]  / answers: 1 / hits: 51208  / 8 Years ago, sun, june 12, 2016, 12:00:00

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 || [];
}
}

More From » arrays

 Answers
24

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.



To be more concise:



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

[#61796] Friday, June 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marint

Total Points: 550
Total Questions: 105
Total Answers: 124

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
;