0

I am trying to update the state in react app

state = {
  pickupAddress: {
    country: '',
    city: '',
    zipCode: '',
    street: '',
  },
  deliveryAddress: {
    country: '',
    city: '',
    zipCode: '',
    street: '',
  },
  parcel: {
    type: '',
    height: '',
    width: '',
    length: '',
    weight: '',
    quantity: '',
  },
};

The problem that i am facing is i cannot reach inside of the object with e.target.pickupAddress.city for example. This is my onChange method

 onChange = (e) => this.setState({[
    e.target.pickupAddress.country]: e.target.pickupAddress.country
});
Chris
  • 57,622
  • 19
  • 111
  • 137
  • 1
    Possible duplicate of [Updating an object with setState in React](https://stackoverflow.com/questions/43638938/updating-an-object-with-setstate-in-react) – Anurag Srivastava Feb 27 '19 at 12:54
  • Try this, onChange = (e) => this.setState({ this.state.pickupAddress.country: e.target.pickupAddress.country }); – Vikas Yadav Feb 27 '19 at 12:54
  • @VikasYadav: That's exact same thing OP has posted in question – huMpty duMpty Feb 27 '19 at 12:56
  • Where is your JSX and the element with this onChange on it? You can't make up properties on e.target like that, I thought e.target would be a standardised DOM Node structure? – Dominic Feb 27 '19 at 12:56
  • The difference with the previous question is that i have multiple objects i want to be able to upgrade the state with one onChange method instead to have to make methods for all cases – George Pantov Feb 27 '19 at 13:05
  • @Dominic, it looks the same but it isn't. – Vikas Yadav Feb 27 '19 at 19:02
  • Thank you for the help but i have found a away around it. I have made onChange method for each object so I don't need to get inside of the main object : ` onChangePickup = (e) => { const newPickupAddress = {...this.state.pickupAddress, [e.target.name]: e.target.value}; this.setState({ ...this.state, pickupAddress: newPickupAddress }) }; – George Pantov Feb 28 '19 at 07:07

0 Answers0