1

I am having an object in state, on change function i want to update the key value in object using setState

this.state= {
  addOfficeObj: {
  name: ''

  }
}

 onOfficeChange(e){
   this.setState({addOfficeObj.name: e.target.value})
 }

onOfficeChange function i am getting e.target.value as "siva" i want to update the addOfficeObj.name as "siva"

  • try using arrow function onOfficeChange(e) to onOfficeChange = e => – FeelRightz Oct 14 '19 at 04:43
  • A great explanation for your question is given here,https://stackoverflow.com/questions/43638938/updating-an-object-with-setstate-in-react – Imtiaz Oct 14 '19 at 04:43

5 Answers5

0

You should do it this way:

onOfficeChange(e){
   this.setState({addOfficeObj:{name: e.target.value}})
}
help-info.de
  • 6,695
  • 16
  • 39
  • 41
Vikash_Singh
  • 1,856
  • 2
  • 14
  • 27
0

You can do it like this:

onOfficeChange(e){
   this.setState({
     addOfficeObj: {
       name: e.target.value
     }
   })
 }
C. J. Tantay
  • 344
  • 1
  • 7
0

Try this, this should work

onOfficeChange(e){
   let addOfficeObj= this.state.addOfficeObj;
   addOfficeObj.name = e.target.value;
   this.setState({
                    addOfficeObj
                })
 }
kiranvj
  • 32,342
  • 7
  • 71
  • 76
0

You can try this.

onOfficeChange(e){
this.setState(prevState => {
  let addOfficeObj = Object.assign({}, prevState.name); 
  addOfficeObj.name = e.target.value; 
  return { addOfficeObj }; 
})
}
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
0

Doing a shallow copy of the top level is not sufficient - the nestedState object should be copied as well.

this.state= {
  addOfficeObj: {
  name: ''
  }
}
onOfficeChange = (e) => {
 this.setState(prevState => ({
    addOfficeObj: {                   // object that we want to update
        ...prevState.addOfficeObj,    // keep all other key-value pairs
        name:  e.target.value         // update the value of specific key
     }
   }))
}

You can do it this way with spread operator , and immutability also remains,(in case you want it )

0xAnon
  • 847
  • 9
  • 20