DEV Community

Discussion on: Creating a CRUD app in React with Hooks

Collapse
 
austejakazlauskyte profile image
Austeja Kazlauskyte • Edited

Hey again!
I have a question.
Let's say my User object not only has fields like Id, Name, and Username, but it also has an Address. Inside the Address field, it has City and ZIP.
In other words, the User has another object inside it.
If I would like to add this User object using a form, how could I reach those second-level properties, like City, in order to update the name?

Thank you for any tips!
Austeja

Collapse
 
sanderdebr profile image
sanderdebr • Edited

Hi no problem!

I would create an exception for your ZIP and City fields. When the name of the fields is one of those, the function will update the user object.

const handleChange = (e) => {
    const { name, value } = e.target;

    if (name === "zip" || name === "city") {
      setUser({ ...user, address: { [name]: value } });
    } else {
      setUser({ ...user, [name]: value });
    }
  };
Enter fullscreen mode Exit fullscreen mode

It is also possible to build a function that searches all the object keys in the user object, and updated the one you want if it finds it but this is a bit more work.

The three dots indicate the object spread, this automatically will create a copy of the object and update the values you want. Another way is to use const draftUser = Object.assign({}, user); to create a copy of the user object. Then you can object this draftUser object and update the state with it :-)

Collapse
 
austejakazlauskyte profile image
Austeja Kazlauskyte

thank you, amazing!