Lovepreet Singh
Lovepreet Singh

Reputation: 390

Delete an item from list in react native and update the new list

I am trying to make a To-Do app in react native. When deleting an item from the list and then try to add a new task in the list, the whole list gets render even the deleted items also. below is my code

arr = []
  state = {
    text : "",
    item : [
      {id:0,data:"Loading ......"}
    ]
  }

  del = (id,data) => {
    this.setState({
      item: this.state.item.filter(item => item.id !== id)
    })
   }
  storeData = async () => {
    this.arr.push({id:Math.random().toString(),data: this.state.text})
    await AsyncStorage.setItem('key',JSON.stringify(this.arr))
    this.setState({
      item: JSON.parse(await AsyncStorage.getItem('key'))
    })
  }
  
   
  async componentDidMount() {
    this.setState({
      item: JSON.parse(await AsyncStorage.getItem('key'))
    })
    this.arr = JSON.parse(await AsyncStorage.getItem('key'))
  }

I even tried to envoke storeData function inside the del function but that is not working. Please help me to resolve this issue.

Upvotes: 0

Views: 573

Answers (1)

cuongtd
cuongtd

Reputation: 3182

You're using this.arr to store item to store in AsyncStorage, but in del function, you forgot to remove item from this.arr. In this case, just use this.state.item is enough, you don't need this.arr

 del = async (id,data) => {
   try {
    const newItem = this.state.item.filter(item => item.id !== id)
    await AsyncStorage.setItem('key',JSON.stringify(newItem))
    this.setState({
      item: newItem
     })
    } catch(err) {}
  }

  storeData = async () => {
    try {
      const newItem = [
         ...this.state.item, 
         {id:Math.random().toString(),data: this.state.text}
      ];
      await AsyncStorage.setItem('key',JSON.stringify(newItem))
      this.setState({
        item: newItem
      })
    } catch(err) {}
  }
  
   
  async componentDidMount() {
    this.setState({
      item: JSON.parse(await AsyncStorage.getItem('key'))
    })
  }

Upvotes: 1

Related Questions