BigSteve
BigSteve

Reputation: 55

Flatlist not re-rendering when data is removed

My react-native flatlist isn't re-rendering when data is removed from the sortedData prop to the flatlist. I tried using the extraData prop to force a re-render, but that didn't work. When I remove the elements, blank rows appear.

handleRemove = (title) => {
    // const start = this.state.people.slice(0, index);
    // const end = this.state.people.slice(index + 1);
    // this.setState({
    //   people: start.concat(end),
    // });
    const filteredData = this.state.sortedData.filter(
      (item) => item.title !== title
    );
    this.setState({ sortedData: filteredData });
  };

  render() {
    const { sortedData } = this.state;

    return (
      <FlatList
        data={sortedData}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => (
          <LeaderboardEntry
            song={item}
            handler={this.handler}
            onRemove={() => this.handleRemove(item.title)}
          />
        )}
      />
    );
  }

Upvotes: 0

Views: 1094

Answers (1)

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16334

You should do like below

 var newSortedData = [...this.state.sortedData];
    newSortedData.splice(index, 1);
    this.setState({
      sortedData: newSortedData,
    });

The reason is even though you are updating the state its pointed to the same array in state so you need to use the spread operator which would create a new array which in turn would cause a re render.

Update Using filter to remove items Your flat list should be changed to

onRemove={() => this.handleRemove(item.title,index)}

Logic for the handle remove function

handleRemove = (title,index) => {
    const filteredData = this.state.sortedData.filter(
      (item,index) => item.index !== in
    );
    this.setState({ sortedData: filteredData });
  };

Here the title parameter is not required at all, you can remove it as well.

Upvotes: 2

Related Questions