bier hier bier hier - 19 days ago 7
React JSX Question

How can I toggle property in reducer?

I have built a cart app with this reducer in reactjs/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 the cart ie open but when I check the logs the cart property is updated and not the cartOpen property?

Answer

Your reducer must always return the complete slice of the app's state for which it is responsible. For TOGGLE_CART, you are only returning the boolean value for openCart.

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

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