Search code examples
reactjsreact-nativekeyasyncstorage

AsyncStorage remove item is not working


I managed to store and manipulate items in asyncStorage but now i am trying to remove a specific item on a button press.

Here is the code :

import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  FlatList,
  Button,
  AsyncStorage
} from "react-native";
import ajax from "./ajax.js";
import PropTypes from "prop-types";
import InspirationList from "./InspirationList";
import FavoriteItem from "./FavoriteItem";
import ProductItem from "./ProductItem";

class Favorites extends Component {
  state = {
    favorites: []
  };

  componentDidMount() {
    this.showProduct();
  }

  async showProduct() {
    let k = 0;
    AsyncStorage.getAllKeys().then(keys =>
      AsyncStorage.multiGet(keys).then(result => {
        let res = [];
        result.map(req => {
          req.forEach(element => {
            k++;
            if (element != null && k % 2 == 0) {
              res.push(JSON.parse(element));
            }
          });
          this.setState({ favorites: res });
        });
        console.log(this.state.favorites);
      })
    );
  }

  async removeItemValue(favi) {
    AsyncStorage.getAllKeys().then(keys =>
      AsyncStorage.multiGet(keys).then(result => {
        result.map(req => {
          req.forEach(element => {
            if (element === JSON.stringify(favi)) {
              AsyncStorage.removeItem(element);
              console.log("they are the same");
            }
          });
        });
      })
    );
  }

  //AsyncStorage.removeItem(element);

  render() {
    return (
      <ScrollView style="styles.fav">
        {this.state.favorites.map(fav => (
          <View key={fav.key}>
            <Text>{fav.nume}</Text>
            <Image
              style={{ width: "100%", height: 500 }}
              source={{ uri: fav.media[0] }}
            />

            <Button
              onPress={() => this.removeItemValue(fav)}
              title="capmare"
              color="#841584"
            />
          </View>
        ))}
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  fav: {
    backgroundColor: "#999",
    flex: 1,
    width: "100%",
    paddingTop: 150
  }
});

export default Favorites;

The method removeItemValue works only if i remove all items. But when i try to remove a specific item, even if it goes inside the if statement and console logs, it does not remove the item.

I tried many methods of removing items and i do not understand why calling the 'removeItem' method works only for the entire array.

Thank you in advance for your help.


Solution

  • It is an async call, so use promise else it will not wait, Also the AsyncStorage.removeItem will give the response as a callback function, so modify like below

    async removeItemValue(favi) {
      AsyncStorage.getAllKeys().then(keys =>
         AsyncStorage.multiGet(keys).then(result => {
           result.map(req => {
             req.forEach(element => {
               if (element === JSON.stringify(favi)) {
                 //calling the promise method written below
                 return this.removeFromAsyncStorage(element)
                 .then(result => {
                   console.log(result);
                 }).catch(err => {
                   console.log(err);
                 });
               }
             });
           });
         })
       );
     }
    
    
    
    removeFromAsyncStorage(key) {
       return new Promise((resolve, reject) => {
         AsyncStorage.removeItem(key, (err, response) => {
          if(response) {
            resolve(response);
          } else {
            reject(err);
          }
        });
       })
     }