HussienK HussienK - 2 months ago 10
React JSX Question

Am I mutating my reducer state by replacing an entire array in an object?

I have a shopping cart app. When I delete an item from the cart, I want to be able to add it back to the cart if the delete request fails.

I do this by storing my previous array of items before deleting an item. And if the request fails to delete the item, I replace back the entire array of items.

Please note, there are multiple orders because the shopping cart can have multiple vendors, each with their own items to add to the cart.

Here's my reducer, that adds back the previous items to the cart if the delete an item request fails.

is an array that is a property of an

My Reducer


return Object.assign({}, state,
state.orders.slice(0, action.orderIndex)
items: action.previousItems
.concat(state.orders.slice(action.orderIndex + 1))

It works, but am I mutating any state here? Or does
take care of that for me?


Object.assign creates a new object shallowly copying the properties from one (or many) objects into a new one.

This means that if your state has nested objects they will be referenced from the new object (although it is a new object, if you remove a property from one it wont affect the other).

If immutability is what you want, I recommend you use Immutable.js