I am trying to update my object using this.setState({dob.year: '1980'})
but this code doesn't work.
getInitialState: function() {
return {
dob: {
'month' : 'January',
'day' : '01',
'year' : '2015'
};
},
I am trying to update my object using this.setState({dob.year: '1980'})
but this code doesn't work.
getInitialState: function() {
return {
dob: {
'month' : 'January',
'day' : '01',
'year' : '2015'
};
},
setState
has no magic in it for expanding paths like dob.year
. It just takes normal javascript objects. If you want to update a sub-state property without touching the rest of the object, you have to do it manually.
this.setState({dob: Object.assign({}, this.state.dob, { year: '1980'} })
Alternatively - you can use object destructuring
this.setState(prevState => {
...prevState,
dob: {
...prevState.dob,
year: '1980'
}
})