简体   繁体   中英

How to update nested value in object using react hooks

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM