Search
  • Kyle

React Native AsyncStorage - Persisting data to Local or Device Storage


We assume you already have the code for a UI screen implemented and we won't bore you with that. But Before showing you the code on how to use AsyncStorage, you should note that

  • AsyncStorage is a key-value storage system that is global to the app.

  • it is unencrypted and asynchronous.

  • It should be used instead of LocalStorage.

At QuickComponent, for all templates, we have used React Native AsyncStorage to give users an excellent offline experience.


Add the dependency to your project using npm or yarn


yarn add @react-native-community/async-storage

The Simple Code


import AsyncStorage from '@react-native-community/async-storage';

const WISHLIST = '@WISHLIST'; //simple key title

const storeWishlist = async (email, data) => {
 const compoundKey = email + WISHLIST;
 try {
 await AsyncStorage.setItem(compoundKey, JSON.stringify(data));
  } catch (err) {
 console.log(err);
  }
};

const retrieveWishlist = async (email) => {
 const compoundKey = email + WISHLIST;
 let result = null;
 
 if (!email) {
  return false;
 }

 try {
 result = await AsyncStorage.getItem(compoundKey);

 if (result !== null) {
 return JSON.parse(result);
    }

 return false;
  } catch (err) {
 console.log(err);
 return false;
  }
};

const deleteWishlist = (email) => {
 const compoundKey = email + WISHLIST;

 AsyncStorage.removeItem(compoundKey);
};

(get a free and premium mobile template with the complete backend at QuickComponent)


Taking advantage of AsyncStorage from React Native, and using an e-commerce store as an example, the methods in the code above simply store, retrieve and delete a user wishlist base on the user email passed.


The methods:


storeWishlist() - this method takes an email and the data to store(wishlist). It uses the email to form a compound key with the already defined simple key (@WISHLIST). This key is used to store a unique record for that particular user.


retrieveWishlist() - This method takes an email and uses that to form a compound key with the already defined simple key (@WISHLIST). This compound key is then used to retrieve the previously stored data that is unique to the email passed.


deleteWishlist() - This method takes an email and uses that to form a compound key with the already defined simple key (@WISHLIST). It uses the key to delete the data(wishlist) belonging to the email passed.


Summary

You might not want to delete a user wishlist after logout. We, therefore, form a compound key with the user email since it is always unique for each user. So if a new user uses this app, the previous user should always find his wishlist available whenever he logs in.


for more information or other methods that you might need, check out the official documentation here


Check out the similar post with an example on React Native AsyncStorage here


#reactnative #ayncstorage #mobileapp #templates

47 views0 comments