My reducer keeps on overwriting the value

Viewed 63

I have a reducer that concats a base price when you click on a menu item, then after when the user clicks on a modifier for that menu item its supposed to add a modifier object to the state but instead it just returns the mod_price object only. I am looking to have it return both the base_price and the mod_price, but instead it returns the mod_price object. Below is my code. Any help would be really appreciated.

/*This shows the cart price for only the selected item next to where it says add to cart*/
export const cartPriceForSelectedItem = (state = [],action) => {

    const {payload,type} = action;

    switch (type) {

        case SELECTED_PRICE :
           const {base_price} = payload;
            return  state.concat({base_price: base_price});

        case SET_MOD_PRICE_TOTAL :
            return  state.concat({mod_price: payload})
    }

    return state;
}
1 Answers

If state is an object, you are looking for spread operator or Object.assign to return the new state with the merged properties.

return  {
    ...state,
    base_price: base_price
};

Object.assign

return  Object.assign({}, state, {
    base_price: base_price
});
       

One thing to note is that these operations perform a shallow merge, which I presume is not an issue in this context.

const initialState = [];
const SELECTED_PRICE = 'SELECTED_PRICE';
const SET_MOD_PRICE_TOTAL = 'SET_MOD_PRICE_TOTAL';

const cartPriceForSelectedItem = (state = [], action) => {

  const {
    payload,
    type
  } = action;

  switch (type) {

    case SELECTED_PRICE:
      const {
        base_price
      } = payload;
      
      return state.concat({
        base_price: base_price
      });

    case SET_MOD_PRICE_TOTAL:
      return state.concat({
        mod_price: payload
      })
  }

  return state;
}


const action1 = {
  type: SELECTED_PRICE,
  payload: {
    "base_price": 20
  }
};
const state1 = cartPriceForSelectedItem(initialState, action1);

console.log('state1', state1);

const action2 = {
  type: SET_MOD_PRICE_TOTAL,
  payload: 45
};
const state2 = cartPriceForSelectedItem(state1, action2);

console.log('state2', state2);

Related