bier hier bier hier - 7 months ago 44
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;
}); = newTotal;
newstate.cartOpen =true
return newstate;

return !state.cartOpen;

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?


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:

    return Object.assign({}, state, {
        cartOpen: !state.cartOpen