Categories
React Answers

How to fix this.setState isn’t merging states as expected with React?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.