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

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

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

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...