0

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'
  };
},
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
kyrilkin
  • 193
  • 1
  • 1
  • 9

1 Answers1

3

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' 
    } 
})

Erick Mwazonga
  • 1,020
  • 12
  • 25
Kyeotic
  • 19,697
  • 10
  • 71
  • 128