React Native AsyncStorage: A Guide to Storing and Managing Local Data

Introduction

When we are building a mobile application, we often need to store data locally for easy access. In React Native, AsyncStorage is a dependency that allows us to store data on our device. This article will focus on how to use Async Storage.  So, without further ado, let's get started,

What is Async Storage?

In React Native, AsyncStorage is a dependency that allows developers to store little chunks of data in a key-value pair on the user's device. AsyncStorage can only store string data types. We can also store object data, but we must serialize it first by using JSON.stringify(). Usually, it is used to store small amounts of data, such as user preferences, authentication tokens, or any other data that needs to be accessed between sessions.

Installation of the AsyncStorage package

To use it, we must first install the AsyncStorage package. This can be done easily with the following commands.

//using npm
npm install @react-native-async-storage/async-storage

//using yarn
yarn add @react-native-async-storage/async-storage

Linking

If you encounter any package linking issues, you can refer to the documentation available on GitHub for guidance and troubleshooting.

AsyncStorage Linking Docs: https://github.com/invertase/react-native-async-storage/blob/master/docs/Linking.md

Troubleshooting

I encountered this error in iOS while working on this. There may be a chance that you will also encounter it,

Error

[@RNC/AsyncStorage]: NativeModule: AsyncStorage is null.

Solution

Go to your project ios folder using the below command,

cd ios

Run the following command after that:

pod install

Importing

After completing the installation process, you must import it into the file where you plan to use it. Simply add the following line to your file to import it.

import AsyncStorage from '@react-native-async-storage/async-storage';

Async Storage API Methods

Async storage provides a variety of API methods which include.

  • setItem
  • getItem
  • mergeItem
  • getAllKeys
  • removeItem
  • multiSet
  • multiGet
  • multiRemove
  • clear

Now we will see using this async storage method how can work so without making any delay. Let’s dive in,

setItem: store single/object string value

The setItem method allows us to store a string or object data in a key-value pair, as shown in the code below.

Store string data

storeData = async (value) => {
    try {
      await AsyncStorage.setItem('username', value);
    } catch (e) {
      console.log("Error: ",e);
    }
  };

Store object data

const user = {
        "name":"MD Sarfaraj",
        "username":"mdsarfaraj",
        "location":"Hyderabad"
      }
storeData = async () => {
    try {
      await AsyncStorage.setItem('user-obj-value', JSON.stringify(user));
    } catch (e) {
      console.log("Error: ",e);
    }
  };

getItem: read single/object string data

The getItem method allows us to retrieve the value associated with a specific key from the storage, as shown in the code below.

Read string data

getData = async () => {

    try {

      const value = await AsyncStorage.getItem('username');

      if (value !== null) {

        console.log("value: ",value);

      }

    } catch (e) {

      console.log("Error: ",e);

    }

  };

Read object data

getData = async () => {

    try {

      const value = await AsyncStorage.getItem('user-obj-value');

      if (value !== null) {

        console.log("User data: ",JSON.parse(value));

      }

    } catch (e) {

      console.log("Error: ",e);

    }

  };

mergeItem: Update the value of the existing key

To update the value of an existing key by merging new data, you can use the mergeItem method. This method can also create a new key with the provided value if it doesn't already exist,  as shown in the code below.

const user1 = {
    "name": "MD Sarfaraj",
    "username": "mdsarfaraj",
    "location": "Hyderabad, India"
  }

  const user2 = {
    "name": "Zeba Khatoon",
    "username": "zebakhatoon",
    "location": "Kolkata, India"
  }

  const mergeTwoObjectData = async () => {
    try {
      await AsyncStorage.setItem('users', JSON.stringify(user1));
      //merged user2 object
      await AsyncStorage.mergeItem('users', JSON.stringify(user2));

    } catch (e) {
      console.log("Error: ", e);
    }
  };

getAllKeys: Retrieve all the keys 

To retrieve an array of all the keys currently stored in the storage, you can use the getAllKeys method, as shown in the code below.

const getAllKeys = async () => {
    let keys = []
    try {
      keys = await AsyncStorage.getAllKeys()
    } catch (e) {
      console.log("Error: ", e);
    }

    console.log(keys)
  }

removeItem: Remove a specific key-value pair

To remove a specific key-value pair from the storage, you can use the removeItem method. Simply pass in the key of the item you want to remove as an argument, as shown in the code below.

const removeUsername = async () => {
    try {
      await AsyncStorage.removeItem('username');
    } catch(e) {
      console.log("Error: ",e)
    }
    getAllKeys(); //after removing get all the keys
  }

multiSet: Store multiple key-value pairs

To store multiple key-value pairs in a single asynchronous operation, you can use the multiSet method. Simply pass an array of key-value pairs as an argument to the method. Here's an example.

const storeMultipleData = async () => {
    const username1 = ["username1", "mdsarfaraj"]
    const username2 = ["username2", "zebakhatoon"]
    try {
      await AsyncStorage.multiSet([username1, username2])
    } catch (e) {
      console.log("Error: ", e);
    }
  }

multiGet: Read multiple keys data

To read multiple key data in a single asynchronous operation, you can use the multiGet method. Simply pass an array of keys as an argument to the method. Here's an example.

const readMultipleData = async () => {
    try {
      const values = await AsyncStorage.multiGet(['username1', 'username2'])
      console.log("Values: ",values)
    } catch (e) {
      console.log("Error: ", e);
    }
  }

multiRemove: Remove Multiple Data

To remove multiple key-value pairs from the storage, you can use the multiRemove method. Simply pass in the array of keys of the items you want to remove as an argument, as shown in the code below.

const removeMultipleData = async () => {
    const keys = ['username1', 'username2']
    try {
      await AsyncStorage.multiRemove(keys)
      //get all the keys after removing
      getAllKeys();
    } catch(e) {
      console.log("Error: ", e);
    }
  }

clear: Remove all the stored data

To remove all data stored in the AsyncStorage, you can use the clear method. This will effectively clear the entire key-value store, removing all data associated with the app. To use this method, simply call it as shown in the code below.

const clearAsyncStorageData = async () => {
    try{
      await AsyncStorage.clear();
      //get all the keys after clear
      getAllKeys();

    }catch(e) {
      console.log("Error: ",e);
    }
  }

Conclusion

If you're developing an application in React Native and require the ability to store small amounts of data locally on the user's device, I recommend utilizing async storage. This feature allows for the storage of data in both key-value pairs and JSON objects, providing flexibility for your needs.

FAQ (Frequently Asked Questions)

Q 1. Can I store complex data structures with AsyncStorage?

Ans. When working with AsyncStorage, it's important to keep in mind that it only supports storing data in a key-value format where both the key and the value are strings. However, there is a way to store complex data structures like objects or arrays by converting them to JSON strings before storing and parsing them back to their original form when retrieving them.

Q 2. Is AsyncStorage secure for storing sensitive data?

Ans. It's important to keep in mind that when using AsyncStorage, data is stored in plain text, which may not be secure for sensitive information. To ensure the safety of your data, it is recommended to use encryption libraries to encrypt the data before storing it in AsyncStorage. This will help protect your information and keep it secure.

Q 3. What is the maximum data limit for AsyncStorage?

Ans. It's important to keep in mind that the data limit for AsyncStorage depends on the available storage space on the device. The limit is not fixed and can vary based on the platform and the device's storage capacity. Since AsyncStorage is designed for storing small amounts of data, it's best to avoid storing large datasets to prevent performance issues and potential storage constraints.

Resources


Similar Articles