Home > Enterprise >  How to create React useState hook matching to JSON object
How to create React useState hook matching to JSON object

Time:12-25

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

CodePudding user response:

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.

  • Related