5

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 ?

0

3 Answers 3

8

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}
}))
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.