Reputation: 7344
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
Upvotes: 1
Views: 1578
Reputation: 166
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();
}
};
Upvotes: 1