Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – How to set a new nested object property using just one line?

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

    {
            "fullName": "John",
            "birthdate": "2000-02-27",
            "cpfNumber": "11408247910",
            "telephoneNumber": "47996034002",
            "emailAddress": "john@gmail.com",
            "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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading