Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  18] [ 5]  / answers: 1 / hits: 75810  / 11 Years ago, sat, september 21, 2013, 12:00:00

I have the following state:


this.setState({ selected: { id: 1, name: 'Foobar' } });  

Then I update the state:


this.setState({ selected: { name: 'Barfoo' }});

Since setState is suppose to merge I would expect it to be:


{ selected: { id: 1, name: 'Barfoo' } }; 

But instead it eats the id and the state is:


{ selected: { name: 'Barfoo' } }; 

Is this expected behavior and what's the solution to update only one property of a nested state object?


More From » reactjs

 Answers
26

I think setState() doesn't do recursive merge.



You can use the value of the current state this.state.selected to construct a new state and then call setState() on that:



var newSelected = _.extend({}, this.state.selected);
newSelected.name = 'Barfoo';
this.setState({ selected: newSelected });


I've used function _.extend() function (from underscore.js library) here to prevent modification to the existing selected part of the state by creating a shallow copy of it.



Another solution would be to write setStateRecursively() which does recursive merge on a new state and then calls replaceState() with it:



setStateRecursively: function(stateUpdate, callback) {
var newState = mergeStateRecursively(this.state, stateUpdate);
this.replaceState(newState, callback);
}

[#75540] Friday, September 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
dominics questions
Wed, Apr 6, 22, 00:00, 2 Years ago
Thu, Jan 13, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
;