pedro almeida
pedro almeida

Reputation: 123

Insert an item in a list inside another in react state

I have this variable on my state:

this.state = {
        itemList: {
            item: [
                {
                    itemAlias: [
                        {
                            name: null
                        }
                    ],
                    idItem: null,
                    itemName: null,
                }
            ]
        }
    }

what I want to do is to insert a new item alias on a cetain item.I did this and its inserting a new itemAlias to my item but is also creates a new Item, and I dont want that, I just want to update my item with a new Item alias:

insertAliasToList = (itm) => {
    let insertedAlias = {
        name: 'test'
    }

    itm.itemAlias.push(insertedAlias)

    this.setState(prevState => ({
        ...prevState,
        itemList: {
            ...prevState.itemList,
            item: [...prevState.itemList.item, p]
        }
    }))
}

I have also tried this but the error Uncaught TypeError: Invalid attempt to spread non-iterable instance appears.

insertAliasToList = (itm) => {
    let insertedAlias = {
        name: 'test'
    }

   // itm.itemAlias.push(insertedAlias)

    this.setState(prevState => ({
        ...prevState,
        itemList: {
            ...prevState.itemList,
            item: {
                ...prevState.itemLIst.item,
                itemAlias:[...prevState.itemList.item.itemAlias,insertedAlias]
            }
        }
    }))
}

Thanks in advance!

Upvotes: 0

Views: 53

Answers (2)

Titus
Titus

Reputation: 22474

You can do something like this:

insertAliasToList = (itm) => {
  let insertedAlias = {
    name: 'test'
  }

  this.setState(prevState => ({
    ...prevState,
    itemList: {
      ...prevState.itemList,
      item: prevState.itemList.item.map(i => {
        if (i.idItem === itm.idItem) {
          return {
            ...i,
            itemAlias: [...i.itemAlias, insertedAlias]
          }
        }
        return i;
      })
    }
  }))
}

It will only work if idItem is unique.

Upvotes: 0

Tameem Safi
Tameem Safi

Reputation: 728

Since you are trying to replace the contents of an item within an array, you will need to first duplicate the array. Then replace what you need within that item using the index and set the state again with the new array.

let insertedAlias = {
  name: 'test'
}

// Duplicate 'item' array
const item = [...this.state.itemList.item]

// Change item using index '0' on the duplicated array
item[0] = {
  ...item[0],
  itemAlias: [
    ...item[0].itemAlias,
    insertedAlias,
  ]
}

// Set state with new item array that contains changes you made
this.setState(prevState => ({
  ...prevState,
  itemList: {
    ...prevState.itemList,
    item: [
      ...item,
    ]
  }
}))

Upvotes: 1

Related Questions