Search code examples
react-nativereact-native-flatlistsetstate

can not use delete functionality in flatlist renderItem


Delete functionality is not working in flatlist renderItem method, but it will work perfectly fine if I use map function to render data instead of flatlsit.

Here is the sample code

class App extends Component {
  state = {
    todos: [
      { todo: 'go to gym', id: 1 },
      { todo: 'buy a mouse', id: 2 },
      { todo: 'practice hash table', id: 3 },
      { todo: 'iron clothes', id: 4 }
    ]
  };

  keyExtractor = item => item.id.toString();

  handleDelete = id => {
    const todos = this.state.todos.filter(item => item.id !== id);
    this.setState({ todos });
  };

  renderItems({ item }) {
    return (
      <View
        style={{
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between'
        }}
      >
        <Text style={{ fontSize: 16 }}>{item.todo}</Text>
        <TouchableOpacity
          onPress={() => this.handleDelete(item.id)}
          style={{ marginRight: 15 }}
        >
          <Text style={{ color: 'red' }}>Delete</Text>
        </TouchableOpacity>
      </View>
    );
  }

  render() {
    return (
      <View>
        {/* {this.renderItems()} */}
        <FlatList
          data={this.state.todos}
          keyExtractor={this.keyExtractor}
          renderItem={this.renderItems}
        />
      </View>
    );
  }
}

I can't understand the reason it gives me the error _this2.handleDelete is not a function.


Solution

  • You were not binding your function, in your constructor bind the function or use array function

    renderItems = ({ item }) => {
    
      return (
        <View
          style={{
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'space-between',
          }}>
          <Text style={{ fontSize: 16 }}>{item.todo}</Text>
          <TouchableOpacity
            onPress={() => this.handleDelete(item.id)}
            style={{ marginRight: 15 }}>
            <Text style={{ color: 'red' }}>Delete</Text>
          </TouchableOpacity>
        </View>
      );
    }