Dominic Martire
Dominic Martire

Reputation: 31

How can I remove an item from a FlatList and then update that list in React Native?

I am making a To Do list app using React Native, where I add events to a FlatList and then have a button that removes that event once it it finished. So far this is what I have. It seems very hacky to me, but most of it works.

import React from 'react';
import { StyleSheet, Text, View, TextInput,TouchableOpacity, FlatList} from 'react-native';


export default class App extends React.Component {

  constructor(props){
    const data = [];
    super(props);
    this.state ={
      text: 'Enter activity here',
      data: data,
      color: true,
      currNum: 0,
    }

  }
  updateText(){
    this.setState({data:this.state.data.concat({key:this.state.text,index:this.state.currNum})});
    this.state.currNum++;

  }
  removeText(item){
    this.setState({data:this.state.data.pop(item.index)});
    this.state.currNum--;

  }
  

  render() {

    return (
      <View style={styles.container}>
        <Text></Text>
        <View style = {{flexDirection:'row',justifyContent:'flex-end'}}>
          <TextInput style = {{fontSize:30,borderColor:'black', flex:1, marginTop:20}} onChangeText = {(text) => this.setState({text})}value = {this.state.text}/>
          <TouchableOpacity style = {{marginTop:20}}onPress = {()=>(this.updateText())}>
            <Text>Add to list</Text>

          </TouchableOpacity>

        </View>

        <View style = {{flex:1, flexDirection:'row'}}>
            <FlatList
              data = {this.state.data}
              extraData = {this.state}
              renderItem = {({item}) => <View><Text style={styles.text} >{item.key}</Text><TouchableOpacity onPress = {() => this.removeText(item)}><Text>Remove</Text></TouchableOpacity></View>}
              />

          </View>

      </View>


    );
  }
}

When I press the "remove" button, I delete an element from the list of data that the FlatList uses. However, whenever I do this I get an error saying "Tried to get frame for out of range index NaN". Is there a way for me to regularly update and remove a FlatList, and to re-render the FlatList once I have removed an item? I have tried using the extraDate prop, but it hasn't worked. I believe I am using it wrong though. Thank you for all the help.

Upvotes: 1

Views: 3744

Answers (2)

Дмитрий Л
Дмитрий Л

Reputation: 21

I think you should use .filter

removeText(item){
    this.setState({
       data: this.state.data.filter((_item)=>_item.key !== item.key)
    });
}

And what this.state.currNum - is for?

Upvotes: 2

Delgee B
Delgee B

Reputation: 166

use this instead you shouldn't mutate this.state and Array.prototype.pop() mutates it

removeText(item, index){
   this.setState({data: [
      ...this.state.data.slice(0, index),
      ...this.state.data.slice(index + 1)
   ]});
   this.state.currNum--;
}

Upvotes: 0

Related Questions