0

I am trying my best to remove an item from my array.

I have attempted to filter it as following:

removeContact(contact) {
this.setState({
   contacts: this.state.contacts.filter((_, i) => i !== contact)
 }); }

But that doesnt seem to do the trick.

My contact is listed in an unordered list like this:

<ul className="list-group">
        {this.state.contacts.map(((contact, index) =>
          <li className="list-group-item" key={`${contact.contact}${index}`}>
            {contact.name} | {contact.phone} | {contact.countryId} <button  onClick={this.removeContact}>Delete</button>
          </li>
          ))
        }

      </ul>

But by clicking remove it just throws an error:

TypeError: Cannot read property 'setState' of undefined

The list to render the contacts from the api works.

1 Answers1

3
removeContact = (index) => () => {
  this.setState({
    contacts: this.state.contacts.filter((_, i) => i !== index)
  }); 
}

I guess you want this. You have to inject index to use inside event listener.

<button onClick={this.removeContact(index)}>
ZeroCho
  • 1,259
  • 9
  • 19