0

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.

1 Answer 1

1

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