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

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

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