Home > Mobile >  React - How to set a new nested object property using just one line?
React - How to set a new nested object property using just one line?

Time:12-05

I'm using a state to store a object with this structure:

    {
            "fullName": "John",
            "birthdate": "2000-02-27",
            "cpfNumber": "11408247910",
            "telephoneNumber": "47996034002",
            "emailAddress": "[email protected]",
            "address": {
                "mainAddress": "Rua Amoroso Costa",
                "numberAddress": "171",
                "neighborHood": "Jardim das Américas",
                "complementInfo": "Casa",
                "zipCode": "81530-150"
            }
      }

I'm using a form to fill this data using the onChange function:

<input type="email" 
   name="emailAddress" 
   id="emailAddress" 
   onChange={(e) => setFormPatient({ ...formPatient, ["emailAddress"]: e.target.value })} />

I have been trying some different approaches to update the data from the address nested object but I'm not getting there. One of my failed intents was:

onChange={(e) => setFormPatient({ ...formPatient, address: "mainAddress": e.target.value })

My question is the following: is there a way to make this one liner work for a nested object like address?

CodePudding user response:

It might be that the object in question is not an array, try to use it like this and check if it works:

 <input type="mainAddress" 
  name="mainAddress" 
  id="mainAddress" 
  onChange={(e) => setFormPatient({ ...formPatient, address: { 
     ...formPatient.address,
     mainAddress: e.target.value 
   }
 })} />

Edit: Fixed based on Chris Heald feedback, ty!

  • Related