Skip to main content

React Native AsyncStorage

React Native AsyncStorage is a simple, unencrypted, asynchronous, persistent, storage system which stores the data globally in the app. It store data in the form of a key-value pair.
React Native recommended to use abstraction on top of AsyncStorage instead of AsyncStorage directly as it operates globally.

On iOS, AsyncStorage is approved by the native code. The iOS native code stores the small values in a serialized dictionary and the larger values in separate files.

On Android, AsyncStorage will use either SQLite or RocksDB based on the availability.
To use the AsyncStorage, import AsyncStorage library as:

  1. import {AsyncStorage} from 'react-native';  

Persist Data:

React Native AsyncStorage saves the data using setItem() method as:

  1. AsyncStorage.setItem('key', 'value');  
Example of persisting the single value:

  1. let name = "Michal";  
  2. AsyncStorage.setItem('user',name);  
Example of persisting multiple values in an object:

  1. let obj = {  
  2.       name: 'Michal',  
  3.       email: 'michal@gmail.com',  
  4.       city: 'New York',  
  5.     }  
  6. AsyncStorage.setItem('user',JSON.stringify(obj));  

Fetch Data:

React Native AsyncStorage fetches the saved data using getItem() method as:

  1. await AsyncStorage.getItem('key');  
Example to fetch the single value:

  1. await AsyncStorage.getItem('user');  
Example to fetch value from an object:

  1. let user = await AsyncStorage.getItem('user');  
  2. let parsed = JSON.parse(user);  
  3. alert(parsed.email);  

React Native AsyncStorage Example 1

In this example, we create the two TouchableOpacity components, one for saving the data and another for retrieving. From first TouchableOpacity component call the savaData() method to save data and from the second TouchableOpacity component call the displayData() method to fetch data.

  1. import React, {Component} from 'react';  
  2. import {Platform, StyleSheet, Text,  
  3.   View,TouchableOpacity, AsyncStorage,  
  4. } from 'react-native';  
  5.   
  6. export default class App extends Component<Props> {  
  7.   saveData(){  
  8.     let name = "Michal";  
  9.     AsyncStorage.setItem('user',name);  
  10.   }  
  11.   displayData = async ()=>{  
  12.     try{  
  13.       let user = await AsyncStorage.getItem('user');  
  14.       alert(user);  
  15.     }  
  16.     catch(error){  
  17.       alert(error)  
  18.     }  
  19.   }  
  20.   render() {  
  21.     return (  
  22.       <View style={styles.container}>  
  23.         <TouchableOpacity onPress ={this.saveData}>  
  24.           <Text>Click to save data</Text>  
  25.         </TouchableOpacity>    
  26.         <TouchableOpacity onPress ={this.displayData}>  
  27.           <Text>Click to display data</Text>  
  28.         </TouchableOpacity>   
  29.       </View>  
  30.     );  
  31.   }  
  32. }  
  33.   
  34. const styles = StyleSheet.create({  
  35.   container: {  
  36.     flex: 1,  
  37.     justifyContent: 'center',  
  38.     alignItems: 'center',  
  39.     backgroundColor: '#F5FCFF',  
  40.   },  
  41. });  

Output:

React Native AsyncStorage React Native AsyncStorage

React Native AsyncStorage Example 2

In this example, we will save the multiple values in the form if JSON object using JSON.stringify(). The JSON.stringify() takes the JavaScript object and convert them into JSON string. On the other hand, JSON.parse() method is used to fetch the AsyncStorage data. This method takes the JSON string and converts it into a JavaScript object before they are returned.

  1. import React, {Component} from 'react';  
  2. import {Platform, StyleSheet, Text,  
  3.   View,TouchableOpacity, AsyncStorage,  
  4. } from 'react-native';  
  5.   
  6. export default class App extends Component<Props> {  
  7.   saveData(){  
  8.     /*let user = "Michal";*/  
  9.     let obj = {  
  10.       name: 'Michal',  
  11.       email: 'michal@gmail.com',  
  12.       city: 'New York',  
  13.     }  
  14.     /*AsyncStorage.setItem('user',user);*/  
  15.     AsyncStorage.setItem('user',JSON.stringify(obj));  
  16.   }  
  17.   displayData = async ()=>{  
  18.     try{  
  19.       let user = await AsyncStorage.getItem('user');  
  20.       let parsed = JSON.parse(user);  
  21.       alert(parsed.email);  
  22.     }  
  23.     catch(error){  
  24.       alert(error)  
  25.     }  
  26.   }  
  27.   render() {  
  28.     return (  
  29.       <View style={styles.container}>  
  30.         <TouchableOpacity onPress ={this.saveData}>  
  31.           <Text>Click to save data</Text>  
  32.         </TouchableOpacity>    
  33.         <TouchableOpacity onPress ={this.displayData}>  
  34.           <Text>Click to display data</Text>  
  35.         </TouchableOpacity>   
  36.       </View>  
  37.     );  
  38.   }  
  39. }  
  40.   
  41. const styles = StyleSheet.create({  
  42.   container: {  
  43.     flex: 1,  
  44.     justifyContent: 'center',  
  45.     alignItems: 'center',  
  46.     backgroundColor: '#F5FCFF',  
  47.   },  
  48. });  

Output:

React Native AsyncStorage React Native AsyncStorage

AsyncStorage Methods

There are various methods of React Native AsyncStorage class which are described below:

Methods

setItem()

  1. static setItem(key: string, value: string, [callback]: ?(error: ?Error)=>void)  
The setItem() sets the value for a key and invokes a callback upon compilation. It returns a Promise object.

getItem()
  1. static getItem(key: string, [callback]: ?(error: ?Error, result: ?string)) =>void)  
The getItem() fetches an item from a key and invokes a callback upon completion. It returns a Promise object.
removeItem()
  1. static removeItem(key: string, [callback]: ?(error: ?Error) => void)  
The removeItem() removes an item for a key and invokes a callback upon compilation. It returns a Promise object.
mergeItem()
  1. static mergeItem(key: string, value: string, [callback]: ?(error: ?Error) => void)  
The mergeItem() merges the existing key's value with the input value and assuming both values are stringified JSON. It returns a Promise object.

NOTE: This method is not supported by all the native implementations.

clear()
  1. static clear([callback]: ?(error: ?Error) => void)  
The clear() method erases all AsynchStorage from all clients, libraries, etc. It is suggested that don't call this, instead of this you may use removeItem or multiRemove to clear only your app's keys. It returns the Promise object.
getAllKeys()
  1. static getAllKeys([callback]: ?(error: ?Error, keys: ?Array<string>) => void)  
It gets all the keys which are known to your app, for all callers, libraries, etc. It returns a Promise object.
flushGetRequests()
  1. static flushGetRequests(): [object Object]  
It flushes any pending request using a single batch call to get the data.
multiGet()
  1. static multiGet(keys: Array<string>, [callback]: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void)  
This method allows you to batch fetching of items given in an array of key inputs. The callback method will be invoked with an array of corresponding key-value pairs found:
  1. multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']])  
The method returns a Promise object.
multiSet()
  1. static multiSet(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)  
This method is used as a batch operation to store multiple key-value pairs. After the completion of operations, you will get a single callback with any errors:
  1. multiSet([['k1', 'val1'], ['k2', 'val2']], cb);  
The method returns a Promise object.
multiRemove()
  1. static multiRemove(keys: Array<string>, [callback]: ?(errors: ?Array<Error>) => void)  
This method calls the batch deletion of all keys in the key array. It returns a Promise object.
multiMerge()
  1. static multiMerge(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)  
It executes the batch of operation to merge existing and new values for a given set of keys. It assumes that the values are stringified JSON. It returns a Promise object.

Note: This method is not supported by all native implementations.

Comments

Popular Posts

Master Map & Filter, Javascript’s Most Powerful Array Functions

Master Map & Filter, Javascript’s Most Powerful Array Functions Learn how Array.map and Array.filter work by writing them yourself This article is for those who have written a  for  loop before, but don’t quite understand how  Array.map  or  Array.filter  work. You should also be able to write a basic function. By the end of this, you’ll have a complete understanding of both functions, because you’ll have seen how they’re written. Array.map Array.map  is meant to transform one array into another by performing some operation on each of its values. The original array is left untouched and the function returns a new, transformed array. For example, say we have an array of numbers and we want to  multiply each number by three . We also don’t want to change the original array. To do this without  Array.map , we can use a standard for-loop. for-loop var originalArr = [1, 2, 3, 4, 5]; var newArr = []; for(var i = 0; i < originalArr.length; i+...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...