When there are a lot of states in a reducer.

When you want to update a single state in a reducer which contains three states, you may probably do this:

1
2
3
4
5
6
// return a new object
return {
  name: 'new name',
  age: state.age,
  gender: state.gender,
}

But what if there are 7 or 8 or tens of states in that reducer? It is not possible to assign every properties to the new object.

Immutable.js will be a good choice for this, it has a set() method, then you only need to update the state you want to update, and use merge() method when you have to update a lot of states.

But if you are not familiar with Immutable.js or you think changing between JS object and ImmutableJS object is a pain in the ass, then use the method below:

1
return Object.assign(target, ...source);

The “target” is the new object we want, and “…source” can includes many objects, and the later objects will cover the former objects:

1
2
3
4
5
6
7
// In this case, 'new name' will replace the name in old state
// and combines the other states in the old state all together to the new object
// bear in mind I'm not saying the old state is changed
// because the states in the store in immutable
return Object.assign({}, state, {
  name: 'new name',
});

Leave a Reply

Your email address will not be published. Required fields are marked *