Home > Enterprise >  How to update nested value in object using react hooks
How to update nested value in object using react hooks

Time:08-09

I am trying to update the nested key and value pair using hooks.

I set the data in useEffect by fetching the API and that is working perfectly fine.

const [data, setData] = useState([]);

data is an object and it looks like this

data
  --- Member
       --- name_1
       --- name_2
       --- mobile
       --- zipcode
  --- id2
  --- id3

I have input box like this

<input name="name_1" className={form.fm_text_m} required value={data.Member.name_1} onChange={handleChange}/>

to update the state I created handleChange

const handleChange = (e) => {
    let name = e.target.name;
    let value = e.target.value;
    setData({
      ...data,'Member':{
        ...data['Member'], name:value
      }});
  }

When I am trying to change the input box, I can not add/remove text from the input box.

but If I replace the setData with this ->

setData({
      ...data,'Member':{
        ...data['Member'], 'name_1':value
      }});

Its working fine

When I replace name variable with the string 'name_1' then it is working but I wanted to use variable so that I dont have to create handleChange for other input box. I have checked console.log(name) and its same as 'name_1'

What I am missing here? Please help.

CodePudding user response:

You have to put name in square brackets:

const handleChange = (e) => {
    let name = e.target.name;
    let value = e.target.value;
    setData({
      ...data,'Member':{
        ...data['Member'], [name]:value
      }});
  }
  • Related