Home > Enterprise >  Reactjs/Javascript update object dynamically
Reactjs/Javascript update object dynamically

Time:10-24

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 update information but it going to remove other keys like task and other, actually it replace not update whole object. I use ...form prevState but wondering how can I keeps prev keys on update. should I use something like ...object ?

Working Demo

CodePudding user response:

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 } });
  • Related