user5604758
user5604758

Reputation:

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

Upvotes: 28

Views: 51556

Answers (5)

Shah
Shah

Reputation: 2894

For anyone with a state set as an Object instead of an Array:

I used reduce() instead of filter() to show another implementation. But ofc, it's up to you how you choose to implement it.

/*
//Implementation of the actions used:

export const addArticle = payload => {
    return { type: ADD_ARTICLE, payload };
};
export const deleteArticle = id => {
     return { type: DELETE_ARTICLE, id}
*/

export const commentList = (state, action) => {
  switch (action.type) {
    case ADD_ARTICLE:
        return {
            ...state,
            articles: [...state.articles, action.payload]
        };
    case DELETE_ARTICLE: 
        return {
            ...state,
            articles: state.articles.reduce((accum, curr) => {
                if (curr.id !== action.id) {
                    return {...accum, curr};
                } 
                return accum;
            }, {}), 
        }

Upvotes: 1

Javier Ramírez
Javier Ramírez

Reputation: 21

In my case filter worked without () and {} and the state was updated

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

Upvotes: -1

ispirett
ispirett

Reputation: 666

You can use Try this approach.

case "REMOVE_ITEM": 
  return {
  ...state,
    comment: [state.comments.filter(comment => comment.id !== action.id)]
  }

Upvotes: 1

Zakher Masri
Zakher Masri

Reputation: 1176

You can use Object.assign(target, ...sources) and spread all the items that don't match the action id

case "REMOVE_ITEM": {
  return Object.assign({}, state, {
    items: [...state.items.filter(item => item.id !== action.id)],
  });
}

Upvotes: 6

Balázs Édes
Balázs Édes

Reputation: 13817

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);

Upvotes: 71

Related Questions