Reputation: 11285
Still pretty new to Redux, and I've gotten decent at saving single values to the store, but I am a bit confused on how to store multiple related properties on an object.
This seems to be related to the use of Object.assign(...
but I'm not sure quite how to do it.
Would the correct method to save additional properties be something like this:
export default (state = {}, action) => {
switch (action.type){
case actionTypes.SAVE_ENGAGEMENT:
return {
...state,
engagement: Object.assign({}, action.engagement)
};
default:
return state;
}
};
Basically I want an object with properties like such in my store:
{
'engagement': 5,
'opened_from_push': true,
'first_accessed_time': 1561927084
}
Ideally I would be able to update it too
Upvotes: 0
Views: 36
Reputation: 2600
You can use the spread operator for your incoming object as well:
const state = {
engagement: 5,
greeting: true
};
const engagement = {
engagement: 6,
opened_from_push: true,
first_accessed_time: 1561927084
}
return { ...state, ...engagment };
Note that the engagement comes second which will override keys, so your state.engagement
will end up as 6 in this example.
Upvotes: 0
Reputation: 1126
Basically, Redux requires you to not mutate the state but return a new one. So I think you just need to do like this.
export default (state = {}, action) => {
switch (action.type){
case actionTypes.SAVE_ENGAGEMENT:
return {
...state,
engagement: action.payload,
};
case actionTypes.SAVE_OPENED_FROM_PUSH:
return {
...state,
opened_from_push: action.payload,
};
case actionTypes.FIRST_ACCESSED_TIME:
return {
...state,
first_accessed_time: action.payload,
};
default:
return state;
}
};
Upvotes: 1