简体   繁体   中英

Set in immutable Map without override the previous value

i'm dispatching an action which sets in the state inside a map an id for a person. My code in the reducer is like this:

const customerSessionReducer = (customerSession = Map(), action) => {
  if (!action) {
    return customerSession;
  }
  switch (action.type) {
    case SET_CUSTOMER_SESSION:
      return customerSession
        .set('customerSession', action.payload.customerID);
    default:
      return Map();
  }
};

When i'm dispatching the action the customerSessionPart of the state is updated without holding the previous value. I want somehow create a Map whose keys contains the customerIDs. I don't want to lose the previous customerIDs Do you have any idea of how to achieve this? For example suppose i dispatch an action for the first time, My customersession has the customerId. When i'm dispatching again my Map is not like {customerID, customerID} but it is lossing the previous value

calling map.set(key, value) will replace the value on the provided key , you have a couple of options:

have a list as the value you are replacing

const previousList = customerSession.get('customerSession');
 //...

 case SET_CUSTOMER_SESSION:
    return customerSession
      .set('customerSession', previousList.push(action.payload.customerID));

use the customerID as the key on that Map

case SET_CUSTOMER_SESSION:
    return customerSession
      .set(action.payload.customerID, 'some-other-value?');

if you don't need to store any other value and you want to have unique values in your store, use a Set instead of a map

const customerSessionReducer = (customerSession = Set(), action) => {
  if (!action) {
    return customerSession;
  }

  switch (action.type) {
    case SET_CUSTOMER_SESSION:
      return customerSession
        .add(action.payload.customerID);
    default:
      return Set();
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM