How to use AsyncStorage in React Native

How to use AsyncStorage in React Native

At the end of this article you’ll have a good grasp on how to use AsyncStorage in React Native using Expo framework.

Hello, fellows!

We will use Expo that enables us to develop our React Native app in the simplest way possible, having a zero setup environment. This is a prerequisite.

We want to persist state whenever we open and close our app. Therefore, we use the AsyncStorage package which gives us the ability to store information asynchronously.

According to the official documentation:

“AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app”

Demo application is going to save the flight destination entered by the user in the storage and retrieve it from the storage. Also, it allows the user to remove saved data.

If you want to play and explore first the app, you can find the complete code here.

Usage

Add this dependency to your package.json:

"@react-native-async-storage/async-storage": “*”

Open the main component App and then import the AsyncStorage library:

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

Next, let’s define a state variable destination containing an empty string default value.

const [destination, setDestination] = useState(‘’);

Storing data

In order to save the destination inside the storage, we will use an asynchronous helper method called saveDestination.

const saveDestination = async () => {
    try {
      await AsyncStorage.setItem('destination', JSON.stringify(destination));
    } catch (e) {
      console.log(e);
    }
  };

AsyncStorage can store only string data, therefore we serialize destination object first using JSON.stringify().

setItem() is used to store the new destination entered by the user and ‘destination’ is the key used to identify this object.

Every time we submit a new destination, we want to save it. For example, useEffect can be of help, by focusing on the changes: whenever destination object changes, data will be saved.

useEffect(() => {
    saveDestination();
  }, [destination]);

Reading data

Saving it is only one part of the story, but how we are going to load our saved destination back in the app?

The following method fetches the stored value, if it exists.

const loadDestination = async () => {
    try {
      const destination = await AsyncStorage.getItem('destination');
      if (destination && JSON.parse(destination).length) { 
        setDestination(JSON.parse(destination));
      }
    } catch (e) {
      console.log(e);
    }
  };

Here, getItem fetches data for ‘destination’ key, if there is any.

However, if there is no data previously stored, as a result of the if condition, no state will be set.

Next effect doesn’t depend on any state, so it will run only once. In this case, loadDestination() will be called once.

useEffect(() => {
    loadDestination();
  }, []);

Removing data

The final step is to allow the user to erase data from the storage.

const removeDestination = async () => {
    try {
      setDestination();
      await AsyncStorage.removeItem('destination');
    } catch (e) {
      console.log(e);
    }
  };

This deletes data previously saved for ‘destination’ key, whenever “CLEAR” button is pressed.

Finally

Check out the source code of this app containing the definition of JSX elements and corresponding styles:

With that said, in this tutorial you have learned how to save, retrieve and delete data using AsyncStorage in React Native and developed a simple functional app. Now, my question is: where is your next flying destination this year? See you in the next post. Until then, bye bye! 😊

If you want to support my work, please consider buying me a coffee. ☕