What Is React Native AsyncStorage and How to Use It?

What Is React Native AsyncStorage and How to Use It?

React Native application, find out how to create this asynchronous and global key-value storage system. Learn here all about React Native AsyncStorage.

Data persistence and storage in a React Native app are made simple with React Native AsyncStorage. Without relying on the device’s local storage or complicated storage systems, you may manage basic scenarios of little data in your app with the help of the AsyncStorage API.

What Is React Native AsyncStorage?

A persistent key-value storage system is provided via the AsyncStorage API. The JavaScript data types supported by the API are string, boolean, numeric, and JSON objects.

When using AsyncStorage, the data remains persistent and accessible even if the app is closed or the device is restarted. For data caching and storing minimal quantities of application state, AsyncStorage is the best storage option.

What Issue Does AsyncStorage Address?

Prior to AsyncStorage, effective data caching was a difficult effort. Either local storage, which loses data when the application shuts down, or a relational database management system (RDBMS) are options for data storage. However, they are too complicated to work in our particular scenario.

These issues are resolved by AsyncStorage, with the skills of React developers who gives React Native applications a quick, dependable way to store small amounts of temporary data.

Data must first be serialised into a JSON string before being stored with AsyncStorage. The JSON string is subsequently kept in a key-value database. Data is deserialized from JSON and given back to you in its original format when you try to get it from AsyncStorage.

These applications are asynchronous and do not interfere with the main JavaScript thread. This makes it perfect for storing information that needs to be accessed frequently, such user settings and application state.

Using AsyncStorage

Run the following command in the terminal of your project to install the react-native-async-storage package:

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

AsyncStorage’s methods do not instantaneously return results because of its asynchronous nature. Instead, they provide back a promise that resolves after the whole process is finished.

When invoking AsyncStorage methods, you must use the async/await syntax or an equivalent method.

Use the setItem() and multiSet() Methods to Write Data

The values for the specified key are set using the setItem() and multiSet() methods. The key and the values are accepted as parameters by these methods.

If the operation was unsuccessful, the method would reject with an error, returning a promise that resolves with a boolean value instead:

// Save a value for the key "user"
await AsyncStorage.setItem('user', 'john');

// Save multiple values for the key "user"
await AsyncStorage.multiSet(['user', 'john', 'doe']);

Use the getItem() and multiGet() Methods to Read Data

Using the key for the desired value, you can retrieve stored data from the storage using the getItem() method. The promise rejects with an error if the passed key does not exist.

const name = await AsyncStorage.getItem('user');

getItem() returns a string as its value. Use JSON.stringify() to turn the data into a string before storing it if you need to store it in a different format. When getting the string, use JSON.parse() to convert it back to the original data type.

// Save the object {name: "John Doe", age: 30} for the key "user"
await AsyncStorage.setItem('user', JSON.stringify({name: "John Doe", age: 30}));

// Get the object for the key "user"
const user = JSON.parse(await AsyncStorage.getItem('user'));

The multiGet() function can also be used to retrieve multiple key-value pairs. The method will require a string-only array of keys.

Using the mergeItem() and multiMerge() Methods to Combine Data

The given value and the current value for the given key are combined using the mergeItem() and multiMerge() methods. Any kind of data can be the value supplied to mergeItem(). AsyncStorage does not encrypt the data, therefore anyone with access to the device can read the data, which is something to keep in mind:

await AsyncStorage.mergeItem('name', 'Jane Doe');

mergeItem() requires the key for the value you would like to merge as well as the new value that you wish to combine with the key’s current value. To merge many items to a key value, use the multiMerge() function.

Simple Storage Making use of the clear() Method

You can delete all of the AsyncStorage items using the clear() method. It can be helpful in a variety of situations, such as when you need to remove cached data from your mobile device or reset the state management of the React app depending a user log-out.

const clearData = async () => {
  try {
    await AsyncStorage.clear();
 
  } catch (e) {
    console.error(e);
  }
};

The code shown above will remove all key-value pairs kept in AsyncStorage.

Additionally, you may instruct clear() to call a callback function that will be used after the procedure is finished.

AsyncStorage.clear()
  .then(() => {
    // Clear operation completed
   
  })
  .catch((error) => {
    console.error(error);
  });

The data stored in AsyncStorage will all be completely deleted if you use the clear() method.

Data Caching Using AsyncStorage

The development of mobile apps frequently uses data caching to enhance performance and minimise network requests. You may quickly cache data in React Native apps with AsyncStorage.

Data is first checked to see if it is already in the cache when you access it. If so, the cache is used to retrieve the data. If not, the programme fetches the information from the more long-term repository and adds it to the cache. The data will be returned from the cache the following time you browse it.

Let’s say you have a mobile app that shows a list of books that was retrieved from an API. You can use AsyncStorage to cache the downloaded book data to improve efficiency.

Here is how it might be done as an illustration:

const [books, setBooks] = useState([]);

useEffect(() => {
    const fetchBooks = async () => {
      try {
        // Check if the cached data exists
        const cachedData = await AsyncStorage.getItem('cachedBooks');

        if (cachedData !== null) {
          // If the cached data exists, parse and set it as the initial state
          setBooks(JSON.parse(cachedData));
        } else {
          // If the cached data doesn't exist, fetch data from the API
          const response = await fetch('https://api.example.com/books');
          const data = await response.json();

          // Cache the fetched data
          await AsyncStorage.setItem('cachedBooks', JSON.stringify(data));

          // Set the fetched data as the initial state
          setBooks(data);
        }
      } catch (error) {
        console.error(error);
      }
    };

    fetchBooks();
  }, []);

In the following example, you retrieve the book data using the useEffect hook. Call AsyncStorage.getItem(‘cachedBooks’) to see if the cached data is present in the fetchBooks function. Use JSON.parse the cached data if it is there.Use setBooks to parse and set it as the default state. This enables you to instantly show the stored data.

Use the fetch() function to get the data from the API if the cached data is missing. Cache the data by using AsyncStorage.setItem() after it has t. After that, make the fetched data the initial state to guarantee that it will be shown in future renderings.

Now, you may see the cached books like follows:

import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const App = () => {
  return (
    <View>
      <Text>Book List</Text>
      <FlatList
        data={books}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View>
            <Text>{item.title}</Text>
            <Text>{item.author}</Text>
          </View>
        )}
      />
    </View>
  );
};

export default App;

The cached data will be displayed without requiring further API requests on subsequent app launches or screen reloads.

React Native AsyncStorage provides a potent solution for data storage and retrieval. Using it for dynamic data loading. Through the use of caching, performance is improved and faster access to stored data is given.

You can dynamically load and show data in your React Native app by combining your understanding of AsyncStorage with strategies like custom pagination. This will make it possible to handle huge datasets effectively.

Schedule an interview with React developers

Conclusion

We have now seen the many ways that AsyncStorage provides, along with instructions on how to use each method and an example use case. Hopefully, this article has made AsyncStorage for React Native more understandable. If you’re looking for expert mobile app development services, consider partnering with a leading mobile app development company in the USA. Their experienced team can help you leverage technologies like AsyncStorage and create high-quality, robust applications that meet your business needs. Thank you for reading!

Frequently Asked Questons (FAQs)

1. How to use asyncstorage in React Native?

React Native AsyncStorage is an easy, unencrypted, permanent, and asynchronous storage system that stores data across the whole app. A key-value pair is used to store data in this system. AsyncStorage operates worldwide, hence React Native advised using abstraction on top of it rather than AsyncStorage directly.

2. Why to use async in React?

A promise-based library called React Async provides a declarative API for making API calls. To support declarative promise resolution and data retrieval, it offers a React component and a React Hook. Nearly all data fetching frameworks and APIs, such as Fetch API, Axios, and GraphQL, are compatible with React Async.

3. What makes async and await different from one another?

A function can be made to appear asynchronous by using the async keyword. The await keyword delays the beginning of the code block of the async function until a promise is accepted or denied.


Book your appointment now

Get in touch






    Stay up-to-date with our blogs