简体   繁体   中英

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. items is an array that is a property of an order object

My Reducer

    case 'ADD_PRODUCT_TO_CART_ERROR':

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

It works, but am I mutating any state here? Or does Object.assign() take care of that for me?

as you are dealing your failed request to delete an item it's good that you are handling it in a completely different case 'ADD_PRODUCT_TO_CART_ERROR': .

and here nothing is mutating as you have concating the previous array with state order it's ok to do that.

indeed it's the right approach to handle such case.

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

The key requirement is that a reducer cannot modify an existing state object; it must produce a new object. You can use functions that returns a new copy of data or if you don't want to take much work with those js immutable functions you can use the library immutable.js .

And this question has some discussion on immutable.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM