andika_kurniawan
andika_kurniawan

Reputation: 567

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 ?

Upvotes: 5

Views: 13828

Answers (3)

Striped
Striped

Reputation: 2547

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

Upvotes: 8

Dennis Nedry
Dennis Nedry

Reputation: 4777

An even simpler solution is to directly destructure recipients current state into the new state like this.

this.setState({
    recipient: {...this.state.recipient, ...temp}
})

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 282030

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

this.setState(prevState => ({
    recipient: {...prevState.recipient, ...temp}
}))

Upvotes: 4

Related Questions