Search code examples
javascriptreact-nativeasyncstorage

How can i remove a selected item from asyncstorage?


I'm making a simple movie watchlist application. I use asyncstorage to save the selected movies. I want to remove the movie the user has selected in the watchlist section. Right now I am trying this code:

    removeItemValue= async (item, index) => {
    let value1 = await AsyncStorage.getItem('movies');
    value1 =JSON.parse(value1);
    console.log("value1"+value)
    //value = item.splice(index,1)
    if (value1 !== null){
        //var index = value.indexOf(x => x.Title === item.Title);
        if (index > -1){
        value1.splice(index, 1);
        await AsyncStorage.removeItem('movies');
        
        AsyncStorage.setItem('movies',JSON.stringify(value)); 
        
    }
    }       
    
}

But this isn't working. Can you tell me where is wrong?

Also my click part: enter image description here


Solution

  • removeItemValue = async(index) => { // don't need item here
      // avoid mutations, create new variables
      const rawValue = await AsyncStorage.getItem('movies');
      try {
        const jsonValue = JSON.parse(rawValue) || []; // avoid undefined or null
        const finalValue = [...jsonValue.slice(0, index), ...jsonValue.slice(index + 1)];
        await AsyncStorage.setItem('movies', JSON.stringify(finalValue)); // add await here
      } catch (e) {
        console.log('Parsing failed', e)
      }
    }
    

    And remove using () => this.removeItemValue(index)