Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading