#StackBounty: #reactjs #json #react-hooks #use-state updating object inside array inside object using prevState and the useState hook

Bounty: 50

I’d like to remove a nested object based on the id is equal to a passed prop. At the moment, the entire object is replaced. I’m missing something, when trying to update the state using useState probably with the way I’m looping my object?

UPDATE: The question was closed in response to available answers for updating nested objects. This question involves arrays which I believe are part of the issue at hand. Please note the difference in nature in this question with the forEach. Perhaps a return statement is required, or a different approach to the filtering on id..

my initial object looks like this:

{
  "some_id1": [
    {
      "id": 93979,
      // MORE STUFF
   
    },
    {
      "id": 93978,
      // MORE STUFF
    }
  ],
  "some_id2": [
    {
      "id": 93961,
      // MORE STUFF
    },
    {
      "id": 93960,
      // MORE STUFF
    }
  ]
}

and I go through each item as such:

for (const key in items) {
        if (Object.hasOwnProperty.call(items, key)) {
            const element = items[key];
            element.forEach(x => {
                if (x.id === singleItem.id) {
                    setItems(prevState => ({
                        ...prevState,
                        [key]: {
                            ...prevState[key],
                            [x.id]: undefined
                        }
                    }))
                }
            })
        }


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.