Explore what’s AsyncStorage about and how to make the most of it

Reading time: 5 minutes

When an app restarts, you don’t want the users to lose all the data or the settings they were using. You want them to be able to find everything as they’ve left it before, with no surprises and no waste of time. This is one of the situations AsyncStorage can solve. AsyncStorage is a pretty straightforward, asynchronous, unencrypted, persistent, and key-value storage tool that can be easily integrated into your React Native application.

Plus, this solution offers multi-platform support; it can be used on Android and Windows as well as on iOS, macOS, and the Web.

This was just a quick overview of what AsyncStore can do for you. If you’ve ever used localStorage or sessionStorage, then AsyncStorage will be an easy-peasy job for you. If you haven’t, don’t worry, we got your back. Let’s dive deep into more details of this storage solution and a guide to installing it. 

A zoom-in to AsyncStorage: what you need to know about this key-value storage solution 

AsyncStorage has data persistence at its core by using key-value pairs, ensuring that the data is saved no matter if you close the app, log out or restart the application. This solution is also asynchronous so that you can make its methods run with your code.

You can store and retrieve data from AsyncStorage without causing trouble to your code. This increases the app’s performance too.

You should be aware that the information is unencrypted. This means that getting the data you need it’s easier since no decryption is required and the stored data isn’t turned into code or encrypted. But this also means that storing sensitive information isn’t a choice here since you can’t really control access, and data can be easily obtained just by getting your phone.

There’s another key you need to learn here: AsyncStorage only accepts and strings data. Before we get started, make sure you keep this in mind. If your data isn’t a string, you’ll need to turn it into string data. In AsyncStorage, key—the name you want to save the data in— and value—the data you store—are strings.

If you need help turning the object you want to save into a string, use JSON.stringify(). If you need to retrieve data from the storage, just use the JSON.parse() and turn it back into object:  

// storing data
const storeUser = async (value) => 
  try 
    await AsynStorage.setItem("user", JSON.stringify(value));
  } catch (error) {
    console.log(error);
  }
};

// getting data
const getUser = async () => {
  try {
    const userData = JSON.parse(await AsynStorage.getItem("user"))
  } catch (error) {
   console.log(error); 
  }
};

Let’s get it installed

First things first: you need to install the AsyncStorage package. So, open up your terminal and run one of these commands:

#using npm

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

#using yarn

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

When you’re done with that, then you’ll have the power to import AsyncStorage inside the React Native component you want to use by retrieving it from the module:

// React Native component

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

How does AsyncStorage interact with React Native async data storage system?

AsyncStorage has methods through which it works and interacts with the React Native async data storage system. Some methods include setItem(), getItem(), mergeItem(), removeItem(), multiGet(), and clear().

Plus, three main actions empower developers to perform and execute actions there. These are: 

  • Set: allows storing data in the async storage by utilizing the key-value pairs.
  • Get: enables getting data values from the async storage by just using the key.
  • Delete: erases the data you want to by using the key.

Going back to the methods, let’s explore how to use each one. If you need to save data to the AsyncStorage, you’ll need to use the setItem() method. In this case, the data is assigned to a string, and that string is the key, and the value object is the data you want to save:

// React Native component
const value = {
    name: "Alex",
    job: "Designer
  };

  const storeUser = async () => {
    try {
      await AsyncStorage.setItem("user", JSON.stringify(value));
    } catch (error) {
      console.log(error);
    }
  };

The getItem() method will enable you to retrieve data from AsyncStorage by just using the key under which the data was saved. Following the previous code example, imagine that you wanna get data back using the key “user”:

// React Native component
const getUser = async () => {
    try 
      const savedUser = await AsyncStorage.getItem("user");
      const currentUser = JSON.parse(savedUser);
      console.log(currentUser);
    } catch (error) {
      console.log(error);
    }
  };

In the meantime, the mergeItem() method can give you a hand when you need to modify or merge a value under a key. Achieving that is just about replacing the value with a new one. In this case, the new one is “Madlein”:

// React Native component
const value = {
    name: "Madlein"
  };

const mergeUser = async () => {
    try 
      await AsyncStorage.mergeItem("user", JSON.parse(value));
    } catch (error) {
      console.log(error);
    }
  };

If you are willing to do some cleaning and delete data from AsyncStorage, you just need to call the removeItem() method. Here it’s all about using the key to delete the stored data:

// React Native component
const removeUser = async () => {
    try {
      await AsyncStorage.removeItem("user");
    } catch (error) {
      console.log(error);
    }
  };

But if the cleaning you want is deeper, you can rely on the clear() method. This erases all the data from AsyncStorage without any key needed:

// React Native component
const removeData = async () => {
    try {
      const savedUser = await AsyncStorage.clear();
    } catch (error) {
      console.log(error);
    }
  };

Getting several pieces of data at once is also possible. For this one, you’ll need to use the multiGet() method because this can deliver you the pieces of data you need from AsyncStorage and return an array of key-value pairs. For instance, if you have user and location data in the storage, the multiGet method can give you both at once:

// React Native component
 const getMultipleData = async () => {
    try {
      const savedData = wait AsyncStorage.multiGet(["location", "user"]);
      console.log(savedData);
    } catch (error) {
      console.log(error);
    }
  };

After running that, it’ll give you an array of the data you want to retrieve with the keys and values. This should look similar to this:

Array(2)
0: (2)  [‘location´, `{“name”: “Buenos Aires”, “country”:“Argentina”}’] 
1: (2) [‘user´, `{“name”: “Alex”, “job”:“Designer”}’] 
length: 2
[[Prototype]]: Array(0)

Now, if the job you need to get done involves storing multiple key-value pairs at once, then you’ll need to use the multiSet method. This will allow you to store your data in arrays. Imagine you need to store data that’s unrelated, something like age and hobbies, you can do that by using:

// React Native component
 const age = {
    name: "Minor",
    number: "Less than 18"
  };

  const hobbies = {
    name: "Reading"
  };

  const firstData = ["age", JSON.stringify(age)];
  const secondData = ["hobbies", JSON.stringify(hobbies)];
  const storeMultipleData = async () => {
    try {
      await AsyncStorage.multiSet([firstData, secondData]);
    } catch (error) {
      console.log(error);
    }
  };

You can also work with the multiRemove() method to remove multiple key-value pairs. To do so, this deletes data in a batch by utilizing an array of keys. Following the last example:

// React Native componen
  const multiRemoveData = async () => {
    try {
      await AsyncStorage.multiRemove(["age", "hobbies"]);
    } catch (error) {
      console.log(error);
    }
  };

Last but not least, if you need to merge multiple pieces of existing data with some new one, then you’re asking for the multiMerge() method. This one does that in a batch:

// React Native component
 const age = 
    name: "Adult",
    number: "More than 18"
  };

  const hobbies = {
    name: "Swimming"
  };

  const firstData = ["age", JSON.stringify(age)];
  const secondData = ["hobbies", JSON.stringify(hobbies)];
  const mergeMultiData = async () => {
    try {
      await AsyncStorage.multiMerge([firstData, secondData]);
    } catch (error) {
      console.log(error);
    }
  };

Ready to try this in your React Native app? If you need more help with React Native or any other tech advice, just search in our blog.