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

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

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...