How can I switch a property in a reducer?

I created a basket application with this reducer in reactions / redux:

const initialState = { items: [], cartOpen: false, total: 0 } const Cart = (state = initialState, action) => { switch (action.type) { case 'ADD_TO_CART': let newstate = [...state, action.payload]; var newTotal = 0; newstate.forEach(it => { newTotal += it.item.price; }); newstate.total = newTotal; newstate.cartOpen =true return newstate; case 'TOGGLE_CART': debugger; return !state.cartOpen; default: return state } } export default Cart; 

I am trying to set the state for a recycle bin i.e. open, but when I check the logs, the cart property is updated, and not the cartOpen property?

+5
source share
2 answers

Redux assumes that you never mutate the objects that it gives you to the reducer. Each time, you must return a new state object . Even if you are not using a library like Immutable , you need to completely avoid mutations.

 case 'TOGGLE_CART': return !state.cartOpen; 

Doing ^^ this mutates your state (damage to your state object). When you do not guarantee immutability, Redux loses predictability and efficiency.

To achieve an immutable state, we can use vanilla Object.assign or its more elegant alternative distribution syntax for objects .

 case 'TOGGLE_CART': return { ...state, cartOpen: !state.cartOpen } 
+7
source

Your reducer should always return the full fragment of the state of the application for which it is responsible. For TOGGLE_CART you only return a boolean for openCart .

Instead, create a copy of the previous state object and update only one property that you want to change:

 case 'TOGGLE_CART': return Object.assign({}, state, { cartOpen: !state.cartOpen }); 
+1
source

Source: https://habr.com/ru/post/1260020/


All Articles