Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS - How to add object inside object

I have this code in constructor :

constructor() {
    this.state = {
        recipient: {
          lat: -6.173752,
          lon: 106.8925773
        }
    }
}

And I want to add this to recipient :

var temp = {
  address: 'example street',
  phone: '+623123131321'
}

How to add temp variable to recipient ?

like image 950
andika_kurniawan Avatar asked Feb 06 '18 16:02

andika_kurniawan


2 Answers

You can override your state using the spread operator

this.state = {
    recipient: {
        ...temp,
        lat: -6.173752,
        lon: 106.8925773
    }
}

Or outside the constructor using setState

this.setState(prevState => ({
   recipient: {...prevState.recipient, ...temp}
}))
like image 118
Striped Avatar answered Nov 15 '22 02:11

Striped


You can make use of spread operator to merge the state values

this.setState(prevState => ({
    recipient: {...prevState.recipient, ...temp}
}))
like image 36
Shubham Khatri Avatar answered Nov 15 '22 03:11

Shubham Khatri