Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an item from Redux state

People also ask

How do you delete item from list in React native?

To delete an item from list with React and JavaScript, we can use some array methods. to create the items state with useState . Then we define the deleteItem function that takes the index of the item to delete and returns a function that calls setItems with (items) => items. filter((_, i) => i !==

Can Redux state be an object?

Designing the State Structure​The root Redux state value is almost always a plain JS object, with other data nested inside of it.


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

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)],
  });
}

You can use Try this approach.

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

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;
            }, {}), 
        }