How to modify a nested object in React?

Asked

Viewed 43 times

0

I’m having trouble modifying the properties of the address, the way it is I can only change the name up to the phone, could someone tell me a way to modify them?

 const dataInit = {
    name: '',
    email: '',
    cnpj: '',
    phone: '',
    address: {
      state: '',
      city: '',
      district: '',
      zip: '',
      obs: ''
    }
  }

  const [clinic, setClinic] = useState(dataInit);
  const onChange = (event) => {
    const { name, value } = event.target;
    setClinic({...clinic, [name]: value });
  }

  const onSubmit = () => {
    const newClinic = {
      name: clinic.name,
      email: clinic.email,
      cnpj: clinic.cnpj,
      phone: clinic.phone,
      address: clinic.address
    }
    props.addClinic(newClinic);
  }
  • if you have not been able to, please ask a mvp of your question in the stackblitz or sandbox code and send us the link. this will facilitate in the resolution

1 answer

0

wouldn’t be like this ?

const onSubmit = () => {
    const newClinic = {
      name: clinic.name,
      email: clinic.email,
      cnpj: clinic.cnpj,
      phone: clinic.phone,
      address: {
       state: clinic.address.state,
        .... 
       }
    }
    props.addClinic(newClinic);
  }
  • But the problem is that this way it picks up empty(' '), my question is about how to edit the address, onsubmit works, the problem is the onChange function that cannot "enter" the address to edit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.