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

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...