Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
How AsyncStorage works
3.
How to install AsyncStorage
4.
AsyncStorage methods
4.1.
Using the setItem() method
4.2.
Using the getItem() method
4.3.
Using the mergeItem() method
4.4.
Using the removeItem() method
4.5.
Using the clear() method
5.
Frequently Asked Questions
5.1.
What is the default Storage Size for AsyncStorage?
5.2.
Why should you use AsyncStorage?
5.3.
The drawback of AsyncStorage?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

React Native AsyncStorage

Author vishal teotia
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In React Native applications, AsyncStorage is a data storage system that is asynchronous and unencrypted. Asynchronous Storage is unencrypted, which means that anyone with access to your device can easily access the data since it's not turned into code nor encrypted. 

Data can be retrieved from the AsyncStorage much easier because it is unencrypted and no further decryption is required. Also, AsyncStorage is asynchronous, which means that its methods run concurrently with your code, and persistent, meaning it is always accessible even when the application is restarted or logged out.

By using AsyncStorage, you can access and use data from any React Native component and increase the app's performance and experience as storing and retrieving data from the AsyncStorage does not interfere with other code executions.

In the same way as localStorage in the web, AsyncStorage persists data via key-value pairs. It will be easy for you to use AsyncStorage if you have used localStorage and sessionStorage before.  

Applications with dark themes are very popular these days, and users love them. It would be better to store the data in AsyncStorage when a user selects dark mode as their preferred theme so they do not have to continuously select it. Even after logging out and logging in later, AsyncStorage retains the persisted data (in this case, the dark theme) until you delete it.

The only thing a developer needs to check is if the dark theme exists in the data storage system; if so, the app theme will automatically become dark, and if not, the light theme will be used.

Click on the following link to read further: Hooks in React JS

How AsyncStorage works

SyncStorage only accepts and stores string data, so if the data is not a string, we must serialize it before storing it. The key and value here are both strings, so we must convert them first to string data before storing them.  

We use JSON.stringify() to convert the object to a string. We use JSON.parse() to convert data back to objects when we receive it from storage:

// 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); 
  }
};

Data for themes or offline data can be stored using AsyncStorage in many scenarios. Nevertheless, sensitive information should not be stored in AsyncStorage because it is not secure. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to install AsyncStorage

We must install the AsyncStorage package before we can use AsyncStorage. Use any of the following commands in your terminal to install the package:

#using npm
npm install @react-native-async-storage/async-storage
#using yarn
yarn add @react-native-async-storage/async-storage

Once imported, you can use it with any component that you want within React Native. Call any method within the module and it will be imported.

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

AsyncStorage methods

There are several ways that AsyncStorage methods work or interact with React Native's async data storage system. AsyncStorage methods offer developers methods for executing actions within the data repository. 

AsyncStorage offers three main actions: Set, Get, and Delete:

  • Set: In async storage, sets or stores data using key-value pairs.
  • Get: By using the key, it retrieves data values from async storage.  
  • Delete: The key is used to delete a particular piece of data or multiple pieces of data.

Using the setItem() method

Data will be saved to the AsyncStorage using the setItem method. Keys are strings that correspond to data or values:

// React Native component
const value = {
    name: "Chimezie",
    job: "Software Developer"
  };
  const storeUser = async () => {
    try {
      await AsyncStorage.setItem("user", JSON.stringify(value));
    } catch (error) {
      console.log(error);
    }
  };

The value object contains the data we wish to save. AsyncStorage only stores strings, so we must first serialize it before saving it. We can do this with JSON.stringify().

Also see,  React Native Reanimated

Using the getItem() method

The key with which data was saved, we can get data back from AsyncStorage using the getItem() method. We receive the data from the key "user" if, for example, we saved the data above using setItem:

// 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);
    }
  };

The value object contains the data we wish to save. AsyncStorage only stores strings, so we must first serialize it before saving it. We can do this with JSON.stringify().

Using the mergeItem() method

By replacing an existing value with a new value, the mergeItem method modifies or merges an existing value under a key: 

// React Native component
const value = {
    name: "Innocent"
  };
const mergeUser = async () => {
    try {
      await AsyncStorage.mergeItem("user", JSON.parse(value));
    } catch (error) {
      console.log(error);
    }
  };

This new value "Innocent" will replace the value in AsyncStorage above.

Using the removeItem() method

AsyncStorage's removeItem() method removes items by deleting their data using the stored key: 

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

Using the clear() method

Clear removes or deletes all the data from AsyncStorage. Since it deletes all the stored data, it does not require a key:

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

Frequently Asked Questions

What is the default Storage Size for AsyncStorage?

The current AsyncStorage size is set to 6MB.

Why should you use AsyncStorage?

As a lightweight solution, it does not require a database, server, or even internet access. After the app closes, the data saved by AsyncStorage remains on the device. It is similar to the local storage used by web applications.  

The drawback of AsyncStorage?

When it comes to saving sensitive data or large amounts of it, we would recommend choosing another alternative.

Conclusion

Since AsyncStorage can be accessed easily, it is not advisable to use it to store sensitive data such as API keys, tokens, user details, etc. Using AsyncStorage is a good and major use case for storing themes. We now know about the different AsyncStorage methods and how to use them with a use case. I hope that this article has helped simplify the AsyncStorage API in React Native.  

Check out this link if you want to explore more about React.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!!

Next article
React Native Async Storage methods
Live masterclass