Ad

Delete Objects From Array In State Using Unique ID

I have list which elements must be deletable (for example with delete button). How can I realize that from react?

this is my state:

state = {
        infos: [
            {
                id: 1,
                info: 'some info',
                deleted: false
            },
            {
                id: 2,
                info: 'some info',
                deleted: false
            },
            {
                id: 3,
                info: 'some info',
                deleted: false
            }
        ]
    }

this is a function for delete that I tried:

removeInfo() {
  this.state.infos.splice(key, 0)
}

this is a jsx code that I get after maping:

{
                      this.state.infos.map((item, key) => {
                          return (
                              <ListItem key={item.key + key}>
                                  <Icon color="gray" f7="home" />
                                  <span className="text-black">{item.info}</span>
                                  <Button><Icon f7="edit" color="#39b549" /></Button>
                                  <Button onClick={this.removeInfo}><Icon color="black" f7="trash" /></Button>
                              </ListItem>
                          )
                      })
                  }
Ad

Answer

You need few changes.

First we need to pass the id of item we want to remove to the remove function:

 <Button onClick={()=>this.removeInfo(item.id)}><Icon color="black" f7="trash" /></Button>

Then you need to remove the item from array in immutable way using setState.

removeInfo(id) {
  this.setState(ps=>({infos:ps.infos.filter(x=>x.id!=id)}))
}

splice mutates the array.

Ad
source: stackoverflow.com
Ad