简体   繁体   中英

Update an object of array using usestate

I have an object like this:

 { name:"lorem ipsum", skills:[] }

Now, I have a form where users add their skills and I want to update the object using usestate hook according to the input of that form

For example, if user adds HTML,CSS and JavaScript in the form, the object should look like this:

 { name:"lorem ipsum", skills:['html','css','JavaScript'] }

How can I achieve this?

You could separate the name and skills into two different variables, but if you insist on keeping it as one object here is what you could do:

 const [obj, setObj] = useState({name:"lorem ipsum",skills:[]}

To initialise your state, and let's say the list of skills you receive from the form is called form_skills:

 setObj({...obj, skills: form_skills})

This makes use of the spread operator which basically copies your object into a new one and replaces all values with the keys you define afterwards, in this case only skills (or adds to the object).

To update each skill separately, you can also ue the spread operator . Just copy the skills array, update the item and set state with new updated array.

 let skills = [...obj.skills]; # makes shallow copy of array skills[i] = 'new value'; setObj({...obj, skills});

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