Sometimes, we want to fix this.setState isn’t merging states as expected with React.
In this article, we’ll look at how to fix this.setState isn’t merging states as expected with React.
How to fix this.setState isn’t merging states as expected with React?
To fix this.setState isn’t merging states as expected with React, we make a copy of the original state object, modify it, and then call setState
with the modified copied object.
For instance, we write
const { selected: _selected } = this.state;
const selected = { ..._selected, name: "Barfoo" };
this.setState({ selected });
to copy the _selected
state with ...
.
Then we add the name
property to it.
Then we assign that to selected
and call setState
with { selected }
to update it.
Conclusion
To fix this.setState isn’t merging states as expected with React, we make a copy of the original state object, modify it, and then call setState
with the modified copied object.