React Native AsyncStorage Component
The following approach covers how to use AsyncStorage in react-native. For this, we are going to use AsyncStorage component. AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app.
Methods in AsyncStorage:
- getItem(): It fetches an item for a key.
- setItem(): It sets an item for a particular key.
- removeItem(): It removes an item for a key.
- mergeItem(): It merges an existing key-value with an input value.
- clear(): It erases all AsyncStorage for all clients, libraries, etc.
- getAllKeys(): It will get all keys known to your app.
- flushGetRequests(): It flushes any pending requests using a single batch call to get the data.
- multiGet(): This allows you to batch the fetching of items given an array of key inputs.
- multiSet(): It uses this as a batch operation for storing multiple key-value pairs.
- multiRemove(): It removes all keys from the keys array.
- multiMerge(): It is a batch operation to merge in existing and new values for a given set of keys.
Now let’s start with the implementation:
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.
expo init myapp
Step 3: Now go into your project folder i.e. myapp
Project Structure: It will look like the following.
For AsyncStorage we have AsyncStorage component in react-native, but that component is now deprecated, So in substitute for this we are going to use an external package called @react-native-async-storage/async-storage. Install that package by using the following command.
npm install @react-native-async-storage/async-storage
Example: Now let’s implement the AsyncStorage. Here we created two buttons the first button set the value and the second button fetch the value.
Start the server by using the following command.
npm run android
Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.