Why I getting a state mutation alert when I'm making a copy of object with spread operator ?
I'm trying to make a shop cart with redux. When adding an element or decrese its quantity I dispatch an action that update de state.
In my reducer if product is not added yet, I return a new copy of state array with the new object. If it is already added, I iterate with map (that returns a new array) and with a copy of product that I'm increasing and its qty property increased.
The problem is with this property What is the correct way to update this property without mutating the state?
reducer
case types.ADD_TO_CART_SUCCESS:
const isAdded = state.cart.find(item => item.sku === action.product.sku);
if (!isAdded) action.product.qty = 1;
return {
...state,
cart: !isAdded
? [action.product, ...state.cart]
: state.cart.map(item =>
item.sku === action.product.sku
? { ...item, qty: ++item.qty }
: item
),
};
Violation warning
Invariant Violation: A state mutation was detected inside a dispatch, in the path: `user.cart.0.qty`. Take a look at the reducer(s) handling the action {"type":"ADD_TO_CART_SUCCESS"....}