Async Storage Package
I use async storage package for long term storage on the device. In this way, the data will be persistent across restarts of my application.
Async storage library lets me store the data as key and value format.
Generally, I use this package to store small-sized data like json objects. If you want to store video, image or other big-sized data, there are other ways to do that.
Installation
I can use the async storage package without any installation but this library is deprecated. So, if I need to use an older version of the react and need to install this library, I can use the command below:
npm i @react-native-community/async-storage
Usage
Importing the Package
import { AsyncStorage } from 'react-native'
Basic Commands
As the name of the package, the functions are asynchronous. So, if you want to wait these functions to complete their jobs we need to use the await keyword.
<key>: I am going to need this variable to identify the data which will be stored. The key variable has to be a string type. It can be anything I want. For example, in this scenario let’s store the token in the async storage.
The following command-line stores the information on the user’s device.
const token = 'abcdefghijklmn'
await AsyncStorage.setItem('token', token)
If I want to get back the stored data, I can use the function below.
const token = await AsyncStorage.getItem('token')
And the final basic function is removing the stored data.
await AsyncStorage.removeItem('token')
Notes
- Async storage library is deprecated
- You can use the V2
External Links
Version 1: https://github.com/react-native-community/async-storage
Version 2: https://github.com/react-native-community/async-storage/tree/master
Async storage implementation for ReactJS: https://www.npmjs.com/package/AsyncStorage