Search code examples
javascriptreactjsreact-nativeasyncstorage

How to delete a specific item from AsyncStorage in react-native?


I want to delete a specific post, but when i click in the button nothing happens, i don't know what i missing

Function

removePost = async (post_id) => {
try {

    const posts = await AsyncStorage.getItem('posts');
    let postsFav = JSON.parse(postsJSON);
    postsItems = postsFav.filter(function(e){ return e.post_id == post_id })
    AsyncStorage.removeItem('posts', postsItems);

} catch(error) {

}};

Button

<Button onPress={this.removePost.bind(this, item.post_id)}>

Solution

  • You can use AsyncStorage.setItem() to update posts with the postItems.

    removePost = async (post_id) => {
    try {
      const posts = await AsyncStorage.getItem('posts');
      let postsFav = JSON.parse(posts);
      const postsItems = postsFav.filter(function(e){ return e.post_id !== post_id });
    
      // updating 'posts' with the updated 'postsItems'
      await AsyncStorage.setItem('posts', JSON.stringify(postsItems));
    
    } catch(error) {
      console.log('error: ', error);
    }};