bukacz
bukacz

Reputation: 25

How to push item into array of object in array with useState?

I have an array with objects that also contain array. How can I push element to that array inside object using useState?

const [list, updateList] = useState([defaultList]);

const defaultList = [
  {
    "name":"Element 1",
    "subList": [{"name": "Element 1"}]
  }
]

How can I update subList in that case?

Upvotes: 1

Views: 1671

Answers (2)

koralarts
koralarts

Reputation: 2112

If you have one item in your array, you must recreate your array with new/modified data in it.

updateList(state => {
  const stateCopy = [...state]

  stateCopy[index] = {
    ...stateCopy[index],
    subList: [...state[index].subList, newItem]
  }

  return stateCopy
})

Update:

If you want to update based on the item name.

updateList(state => {
  const stateCopy = [...state]
  const indexOfName = stateCopy.findxIndex(item => item.name === name)

  stateCopy[indexOfName] = {
    ...stateCopy[indexOfName],
    subList: [...state[indexOfName].subList, newItem]
  }

  return stateCopy
})

Upvotes: 1

Luke Willis
Luke Willis

Reputation: 8580

Assuming you want to append an item to the sublist of a specific list item, based on index:

function appendSublistItemForItemAtIndex(newItem, index) {
  updateList([
    ...list,
    [index]: {
      ...list[index],
      subList: [
        ...list[index].subList,
        newItem
      ]
    }
  ])
}

Then call this function wherever needed for your component (some callback, in a useEffect hook, etc.)

Upvotes: 1

Related Questions