0

I have an object:

const [form, setForm] = useState({});

And in useEffect it will update form:

let obj = {
  id:1,
  info: {information: 1, task: 2, other: 3}
}

setForm(obj)

And I want to update this object values by this function handleForm:

const handleForm = (name, value, type, object) => {
  if(object){
      setForm({...form, [object]: {[name]: value}})
  } else {
      setForm({...form, [name]: value});
  }
}

Here is for example I update a key's value:

<Input value={obj.info.information} onChange={(e)=>handleForm('information', e.target.value, false, 'info')}/>

By this, I want to update info object, information key's value. It works and updates information but it going to remove other keys like task and other, actually it replaces not updating the whole object. I use ...form prevState but wondering how can I keeps prev keys on update. should I use something like ...object ?

Working Demo

1 Answer 1

1

In your handleForm when condition for object is hit, you replace the whole object with a single value. Instead, you want to spread existing values and add the new one to it, like so:

      setForm({ ...form, [object]: { ...form[object], [name]: value } });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.