Using concat on redux state still modifies state

Viewed 42

I am trying to modify some states to have them displayed differently but I can't seem to modify it without getting an error telling me to not mutate the state. I have tried using .concat, .slice, and the spread operator to copy the state array but it doesn't seem to work.

const { cart, totalCartPrice, totalItemsInCart } = useSelector(
    (state) => state
  );

  const cartHandler = () => {
    const copyCart = cart.concat();
    copyCart[0].name = "New Name"
    setDisplayCart(copyCart)
  };
Doing it this way won't necessarily throw an error but it will mutate the state. If I dispatch an action with a button I set up, it will then throw an error about the state being mutated.

1 Answers

If you totally want to change this object without mutating the state:

    const copyCart = {...cart[0]};
    copyCart.name = "New Name"
  • If you want to keep this in the state, this part should be in a reducer
  • If you want to derivate this value from the state, this should be done in a selector

Update state with redux

Moreover, this is better to do this inside a reducer as it seems you want to keep this change in the state.

If you are using redux-toolkit with immer, this is the only place where it's safe to "mutate" the state

createReducer(0, {
  changeName: (state, action: PayloadAction<string>) => {
    state.cart[0].name = action.payload
  },
})

Then you can use it like this:

dispatch(changeName("New Name"));
Related