Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting object elements from array using splice react native

I am trying to add and delete an obect from an array, I have been able to figure out the add object part, but the deletion is not working. I have used filter() but it did nothing. Now I am using splice, it works but it deletes the first element, instead of the selected item. below is a sample code, and I have shown only the functions for better clarity.

        handleDelete(item) {

          this.setState(({ list}) => {
            const newList = [...list];
            newList.splice(item.key, 1);
            console.log('deleted', newList);
            return { list: newList };
          });
        }


        handleAdd() {
          const { firstname, lastname, email, phone} = this.state;
          const ID = uuid();
          const newItemObject = {
              key: ID,
              firstname: firstname,
              lastname: lastname,
              email: email,
              phone: phone,
              image: null,
          };

          this.setState(prevState => ({
            list: [...prevState.list, newItemObject]
          }));
        }

I would like to

like image 387
vincent O Avatar asked Jun 06 '26 02:06

vincent O


1 Answers

The item's key and index in the array are probably not the same. If the item is in the array, you can use Array.indexOf() to find it's index, and splice it out:

handleDelete(item) {
  this.setState(({ list }) => {
    const newList = [...list];
    const index = newList.indexOf(item);
    newList.splice(index, 1);

    return {
      list: newList
    };
  });
}

Or if you want to use Array.filter(), check if the key of of current element (o) is different from that of item:

handleDelete(item) {
  this.setState(({ list }) => ({
    list: list.filter(o => o.key !== item.key)
  }))
}
like image 61
Ori Drori Avatar answered Jun 08 '26 15:06

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!