React Native AsyncStorage is an effortless, unencrypted, asynchronous key- value pair module that enables one to carry on data without the need of cloud storage and operate offline in React Native applications. The data is available globally to the application. Since it is available globally. It can be seen as a data storage solution for iOS, MacOS, Web, Windows and Android. It enables one to simplify saving data, merging, reading and deleting data at will.
As a developer from a react native development agency, one needs to know the limitations of an AsyncStorage module. One such limitation is that on Android the database size is set to 6MB limit by default. As Asyncstorage is based on SQLite, one also needs to be wary of the SQLite limitations. So using Asyncstorage one can only store small values in the key-value pair storage system. One can store the interested value with respect to any key and then can access the value using the same key again.
Being able to operate offline, this module has numerous instances where its usage is quite helpful. The main use case scenarios is managing sessions. You might have noticed that many applications need your login credentials for the first time you enter the application. The apps don’t ask you for the credentials, i.e., you don’t need to login again. But in reality, there is a high probability that your credentials are retrieved from the React Native AsyncStorage and you are re-logged into the app. This enables you to go to the next screen without login. This is what session management is.
To get more info about leading react native development agency regarding session management, click here. Let’s get started with a simple Asyncstorage implementation where we will persist the entered name.
Setting up
React Native version 60+ has many packages and they can be installed easily using the npm package manager.We will start with creating a React Native project and install the module.Open the terminal window and run the following commands in the given sequence:
# creating a new react-native app
npx react-native init rnAsyncStorageExample
# going to the project directory
cd rnAsyncStorageExample
# installing the async-storage module
npm install -S @react-native-community/async-storage
For iOS, cocoapods should be installed to handle linking the module with the native binaries. Run this below command to install cocoapods for iOS.
#navigating to ios directory and installing cocoapods
cd ios/ && pod install
# returning to the root directory
cd ..
Using the AsyncStorage API
Now we will create a demo application that saves a value entered by the user as input and retrieve the value from the storage. This will be accomplished by using Asyncstorage API functions. To get started import the below mentioned components.
import React, { useState, useEffect } from ‘react’;
import {
StyleSheet,
View,
Text,
TextInput,
TouchableOpacity
} from ‘react-native’;
import AsyncStorage from ‘@react-native-community/async-storage’;
Let us define a KEY variable that facilitates reading and saving the data with the help of API functions. This variable is the key that acts as an identifier to the value that will be stored.
const KEY = ‘@save_name’;
We will define a state variable “name” inside the App functional component. Its default value is empty string.
const App = () => {
const [name, setName] = useState(”);
//..
}
export default App;
Storing the data
We will save the data with the help of asynchronous helper method “saveData”. As this is a promise-based method, we can use the “async-await” syntax with the “try-catch” block.
We will pass the identifier “KEY” as well the state variable – “name” to AsyncStorage.setItem(). This stores the value in the storage. We can display an alert box on the status of data we wanted to store – whether got stored successfully or not.
const saveData = async () => {
try {
await AsyncStorage.setItem(KEY, name)
alert(‘Data saved successfully’)
} catch (e) {
alert(‘Data failed to be stored ‘)
}
}
Retrieving the data
The app should be able to read the data stored when it restarts. To do that we are going to define another function called “retrieveData”. We will use AsyncStorage.getItem() to retrieve the stored value from the storage. We will save the value of the state variable “name” only when its value is not null.
const retrieveData = async () => {
try {
const userAge = await AsyncStorage.getItem(KEY)
if (userAge !== null) {
setName(userName)
}
} catch (e) {
alert(‘Unable to retrieve data’)
}
}
Removing the stored data
We might want to delete the stored value at some point. To achieve this we will use the clear() method from the AsyncStorage API.
const clearStorage = async () => {
try {
await AsyncStorage.clear()
alert(‘Storage successfully cleared!’)
} catch (e) {
alert(‘Unable to clear data’’)
}
}
Mastering the input
We will use two more methods onVarianceText and onRequestEdit. They help in reading and updating the state variable as well as storing the user’s input.
const onVarianceText = userName => setName(userName)
const onRequestEdit = () => {
if (!name) return
saveData(name)
setname(”)
}
Finishing the application
We will complete the rest of the application, i.e, its front end.
const App = () => {
// … rest of the code remains the same
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>Android App</Text>
</View>
<View style={styles.panel}>
<Text>Enter your name here:</Text>
<TextInput
style={styles.input}
value={name}
placeholder=””
onVarianceText={onVarianceText}
onRequestEdit={onRequestEdit}
/>
<Text style={styles.text}>Hello {name}</Text>
<TouchableOpacity onPress={clearStorage} style={styles.button}>
<Text style={styles.buttonText}>Clear Storage</Text>
</TouchableOpacity>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1
},
header: {
width: ‘100%’,
backgroundColor: ‘#dcdcdc’,
padding: 20,
borderBottomWidth: StyleSheet.hairlineWidth,
alignItems: ‘center’
},
title: {
fontSize: 22,
color: ‘#333’,
fontWeight: ‘bold’
},
panel: {
paddingTop: 40,
alignItems: ‘center’
},
text: {
fontSize: 24,
padding: 10,
backgroundColor: ‘#dcdcdc’
},
input: {
padding: 15,
height: 50,
borderBottomWidth: 1,
borderBottomColor: ‘#333’,
margin: 10
},
button: {
margin: 10,
padding: 10,
backgroundColor: ‘yellow’
},
buttonText: {
fontSize: 18,
color: ‘#444’
}
})