Salvo
Salvo

Reputation: 107

removing item from Flatlist

I need to make a function to remove items from a Flatlist, this below is the one I'm using, but instead of deleting the item, it adds the same one again:

removeItem = (key) => {
    let filteredItems = this.state.workoutList.filter(item => item.key !== key);
    this.setState({ workoutList: filteredItems })
  }

and this what shows in the Terminal when I run it:

Array [
  Object {
    "Friday": false,
    "Monday": true,
    "Saturday": false,
    "Sunday": false,
    "Thursday": false,
    "Tuesday": false,
    "Wednesday": false,
    "key": 0.3257222928276463,
    "workoutName": "",
  },
]

Upvotes: 0

Views: 182

Answers (1)

Gabriel Augusto
Gabriel Augusto

Reputation: 507

I think you cannot change a state variable directly, you need to use Object.assign() to make a copy of this array from state to manipulate it.

removeItem = (key) => {
   let filteredItems = Object.assign([], this.state.workoutList).filter(item => item.key !== key);
   this.setState({ workoutList: filteredItems })
}

should do the job

Upvotes: 1

Related Questions