简体   繁体   中英

How to create React useState hook matching to JSON object

I am trying to create a useState hook matching to this object:

[
   {
      "id":"",
      "name":""
   }
]

This is how my code is looking like:

  const [ galleries, setGalleries ] = useState([
    {
      id: "",
      name: ""
    }
  ])
setGalleries({...galleries, id: gallery.id, name: gallery.name})

Here's how you can add a new object to the state array

setGalleries((previousGalleries) => [...previousGalleries, {
  id: gallery.id,
  name: gallery.name
}])

Problem in your code

setGalleries({...galleries, id: gallery.id, name: gallery.name})

galleries is an array but you're spreading it in an object. A separate object is also not created for adding the new gallery.

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