Is this the correct way to delete an item using redux?

CWright picture CWright · Jan 4, 2016 · Viewed 91.7k times · Source

I know I'm not supposed to mutate the input and should clone the object to mutate it. I was following the convention used on a redux starter project which used:

ADD_ITEM: (state, action) => ({
  ...state,
  items: [...state.items, action.payload.value],
  lastUpdated: action.payload.date
})

for adding an item - I get the use of spread to append the item in the array.

for deleting I used:

DELETE_ITEM: (state, action) => ({
  ...state,
  items: [...state.items.splice(0, action.payload), ...state.items.splice(1)],
  lastUpdated: Date.now() 
})

but this is mutating the input state object - is this forbidden even though I am returning a new object?

Answer

David L. Walsh picture David L. Walsh · Jan 4, 2016

No. Never mutate your state.

Even though you're returning a new object, you're still polluting the old object, which you never want to do. This makes it problematic when doing comparisons between the old and the new state. For instance in shouldComponentUpdate which react-redux uses under the hood. It also makes time travel impossible (i.e. undo and redo).

Instead, use immutable methods. Always use Array#slice and never Array#splice.

I assume from your code that action.payload is the index of the item being removed. A better way would be as follows:

items: [
    ...state.items.slice(0, action.payload),
    ...state.items.slice(action.payload + 1)
],