DEV Community

Discussion on: Creating a CRUD app in React with Hooks

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!