Reputation: 567
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
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
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
Reputation: 282030
You can make use of spread operator
to merge the state values
this.setState(prevState => ({
recipient: {...prevState.recipient, ...temp}
}))
Upvotes: 4