Zac
Zac

Reputation: 12836

Add new child objects to existing object in React

I am trying to update through useState a child object with an additional object. I created an example to make this more clear :

https://codesandbox.io/s/affectionate-wescoff-u01x0?file=/src/App.js

The example object looks like :

{
  "id": 123,
  "books": {
    "book": {}
  }
}

When I push more data in I want it to look like this :

{
  "id": 123,
  "books": {
     "book": {
      "name": "Sirens of Titan",
      "author": "Kurt Vonnegut"
      },
     "book": {
      "name": "The Hobbit",
      "author": "J.R.R. Tolkein"
    }
  }
}

At this stage I have it pretty messed up and it looks like :

{
   "id":123,
   "books":[
      {
         "0":{
            "book":{
               
            },
            "sampleData1":{
               "book":{
                  "name":"Sirens of Titan",
                  "author":"Kurt Vonnegut"
               }
            }
         },
         "sampleData2":{
            "book":{
               "name":"The Hobbit",
               "author":"J.R.R. Tolkein"
            }
         }
      }
   ]
}

This is the way I set that broken object :

  const [main, setMain] = useState(library);

  function addNestedObj() {
    setMain({ ...main, books: [{ ...main.books, sampleData1 }] });
  }

Upvotes: 0

Views: 484

Answers (2)

Robin Zigmond
Robin Zigmond

Reputation: 18249

Just take the destructuring a stage further:

setMain({...main, kids: [...main.kids, secondObj]})

Upvotes: 2

Merlin04
Merlin04

Reputation: 2317

The books property of your library object was an object, not an array. This might have been necessary but I guessed that it isn't since your book objects already have a name property, so they don't need a separate key.

With that change, you can modify your setMain function to add the book property of the sampleData to the books property of your state:

setMain({ ...main, books: [...main.books, sampleData1.book] });

I've added these changes in a fork of your CodeSandbox: https://codesandbox.io/s/modest-fog-byegh?file=/src/App.js

Upvotes: 1

Related Questions