Merging states in Redux store
Sometimes I have found I have an object in my Redux store which has multiple children properties and I need to update some of the object properties but keep the rest the same i.e. I need to merge 2 states together.
If this is how our Redux store looked to start with: currentState
{
profile: {
title: 'Mr',
firstName: 'Jose',
lastName: 'Mourinho'
}
}
And our new state was like this: changeState
{
profile: {
firstName: 'Ole',
lastName: 'Solksjaer'
}
}
To merge these states we can use the assign method. I have created a React method that returns the merge of the 2 states.
const assign = Object.assign || require('object.assign');
_mergeCurrentState(currentState, change) {
return assign(currentState, change);
}
We can call it like this and pass it straight into our changeProfileData Redux action:
this.props.dispatch(actions.changeProfileData(
this._mergeWithCurrentState(currentState, changeState)
));
Our changeProfileData action looks like this:
export function changeProfileData(newState) {
return { type: 'PROFILE', newState };
}
Our reducer would look something like this:
export default function data(prevState = {}, action) {
switch (action.type) {
case 'PROFILE':
return assign({}, prevState, {
profile: action.newState
});
default:
return prevState;
}
}
Our new Redux store data would look like the following. The title hasn't changed but the 'firstName' and 'lastName' have been updated.
{
profile: {
title: 'Mr',
firstName: 'Ole',
lastName: 'Solksjaer'
}
}