Table of contents
1.
Introduction
1.1.
Essential facts about React Native AsyncStorage
2.
Installation
2.1.
Importing the AsyncStorage library in code:
3.
Storing the data
3.1.
Storing String value:
3.2.
Storing Object Value:
4.
Fetching the data
4.1.
Fetching String value:
4.2.
Fetching Object Value:
5.
Methods
5.1.
getItem()
5.2.
setItem()
5.3.
removeItem()​
5.4.
mergeItem()
5.5.
clear()
5.6.
getAllKeys()
5.7.
flushGetRequests()
5.8.
multiGet()​
5.9.
multiSet()
5.10.
multiRemove()
5.11.
multiMerge()
6.
 
7.
 
8.
 
9.
 
10.
 
11.
 
12.
 
13.
 
14.
 
15.
 
16.
 
17.
 
18.
 
19.
 
20.
 
21.
 
22.
Frequently Asked Questions
22.1.
What is AsyncStorage in React Native?
22.2.
Is React Native async storage safe?
22.3.
Which method is used for storing data in AsyncStorage in React Native?
22.4.
How do you save an object in async storage react native?
22.5.
How do I reset my async storage?
23.
Conclusion
Last Updated: Mar 27, 2024

React Native Async Storage methods

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

AsyncStorage is a simple key-value storage system that is unencrypted, asynchronous, and persistent. It enables offline data persistence in React Native apps. It should be preferred over LocalStorage.

Essential facts about React Native AsyncStorage

  • AsyncStorage runs worldwide, and it is advised that you utilize an abstraction on top of it rather than AsyncStorage directly for anything more than moderate usage.
     
  • Async Storage can only store string data. To store object data, you must first serialize it before storing it. For data that can be serialized to JSON, use JSON.stringify() when saving the data and JSON.parse() when loading the data.
     
  • On iOS, native code backs AsyncStorage, which stores small data in a serialized dictionary and larger data in separate files. AsyncStorage on Android will utilize either RocksDB or SQLite, depending on availability.
     
  • The JavaScript code for AsyncStorage is a layer that provides a straightforward JavaScript API, actual Error objects, and non-multi functions. The API produces a Promise object for each method.
     

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

Installation

Many of React Native's API modules are available as separate packages in version 0.60.0+, which you can install with a package manager like npm or yarn. According to the React Native documentation, you should directly use the @react-native-community/async-storage instead of the AsyncStorage object.

Let's start by making a new React Native project and installing the module. Execute the following commands in the sequence listed from a terminal window.

# create a new react-native app
npx react-native init rnExample

# move inside the project directory
cd rnAsyncStorageExample

# install the async-storage module
yarn add @react-native-async-storage/async-storage

# Or is you prefer to use npm
npm install @react-native-async-storage/async-storage

Auto Linking has been enabled for React Native versions 0.60 and up, so we no longer need to link the library; nevertheless, for iOS, you must install cocoapods and run the following command:

npx pod-install ios

Importing the AsyncStorage library in code:

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

Storing the data

setItem() is used to create new data items (where none exist) and edit existing data items.

Storing String value:

const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('@storage_Key', value)
  } catch (e) {
    // saving error
  }
}

Storing Object Value:

const storeData = async (value) => {
  try {
    const jsonValue = JSON.stringify(value)
    await AsyncStorage.setItem('@storage_Key', jsonValue)
  } catch (e) {
    // saving error
  }
}

Fetching the data

getItem() delivers a promise that resolves to a stored value if data for the specified key is discovered or returns null otherwise.

Fetching String value:

const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

Fetching Object Value:

const getData = async () => {
  try {
    const jsonValue = await AsyncStorage.getItem('@storage_Key')
    return jsonValue != null ? JSON.parse(jsonValue) : null;
  } catch(e) {
    // error reading value
  }
}

Methods

The React Native AsyncStorage class has several methods, which are listed below:

getItem()

Fetches an item for a key and, when finished, invokes a callback. This method returns a Promise object.

static getItem(key: string, [callback]: ?(error: ?Error, result: ?string) = > void)

setItem()

Sets the value for a key and then calls a callback when it's done. This method returns a Promise object.

static setItem(key: string, value: string, [callback]: ?(error: ?Error) = > void)

removeItem()

Removes an item for a key and then triggers a callback upon completion. This method returns a Promise object.

static removeItem(key: string, [callback]: ?(error: ?Error) => void)

mergeItem()

Merges a current key value and an input value, both of which must be stringified JSON. This method returns a Promise object.

static mergeItem(key: string, value: string, [callback]: ?(error: ?Error) => void)

NOTE: Not all native implementations support this.

Example:

let UID_object = {
 name: 'Avinash',
 age: 21,
 traits: { hair: 'black', eyes: 'black' }
};
// Define what will be added or updated
let UID_delta = {
 age: 31,
 traits: { eyes: 'blue', shoe_size: 10 }
};

AsyncStorage.setItem(
 'UID123',
 JSON.stringify(UID_object),
 () => {
   AsyncStorage.mergeItem(
     'UID123',
     JSON.stringify(UID_delta),
     () => {
       AsyncStorage.getItem('UID123', (err, result) => {
         console.log(result);
       });
     }
   );
 }
);

// Console log result:
// => {'name':'Avinash','age':21,'traits':
//    {'shoe_size':10,'hair':'black','eyes':'blue'}}

clear()

Removes all AsyncStorage from all clients, libraries, and other applications. To clean only your app's keys, use removeItem or multiRemove instead of using this. This method returns a Promise object.

static clear([callback]: ?(error: ?Error) => void)

getAllKeys()

It gets all keys that your app is aware of; for all callers, libraries, etc. This method returns a Promise object.

static getAllKeys([callback]: ?(error: ?Error, keys: ?Array<string>) => void)

flushGetRequests()

To acquire the data, it flushes any pending requests with a single batch call.

static flushGetRequests(): [object Object]

multiGet()

static multiGet(keys: Array<string>, [callback]: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void)

This allows you to fetch objects in bulk using an array of key inputs. With an array of corresponding key-value pairs identified, your callback will be called The method returns a Promise object:

multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']])

Example:

AsyncStorage.getAllKeys((err, keys) => {
 AsyncStorage.multiGet(keys, (err, stores) => {
   stores.map((result, i, store) => {
     // get at each store's key/value so you can work with it
     let key = store[i][0];
     let value = store[i][1];
   });
 });
});

multiSet()

static multiSet(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)

This can be used to store many key-value pairs in a batch operation. You'll get a single callback with any problems after the operation is finished. The method returns a Promise object:

multiSet([['k1', 'val1'], ['k2', 'val2']], cb);

multiRemove()

This method is used to delete all keys in the keys array in one go. This method returns a Promise object.

static multiRemove(keys: Array<string>, [callback]: ?(errors: ?Array<Error>) => void)

Example:

let keys = ['k1', 'k2'];
AsyncStorage.multiRemove(keys, (err) => {
 // keys k1 & k2 removed, if they existed
 // do most stuff after removal (if you want)
});

multiMerge()

Merge existing and new values for a collection of keys in a batch operation. This implies that the values are stringified JSON. This method returns a Promise object.

static multiMerge(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)

NOTE: Not all native implementations support this.

Example:

// first user, initial values
let UID234_object = {
 name: 'Chris',
 age: 30,
 traits: { hair: 'brown', eyes: 'brown' }
};

// first user, delta values
let UID234_delta = {
 age: 31,
 traits: { eyes: 'blue', shoe_size: 10 }
};

// second user, initial values
let UID345_object = {
 name: 'Marge',
 age: 25,
 traits: { hair: 'blonde', eyes: 'blue' }
};

// second user, delta values
let UID345_delta = {
 age: 26,
 traits: { eyes: 'green', shoe_size: 6 }
};

let multi_set_pairs = [
 ['UID234', JSON.stringify(UID234_object)],
 ['UID345', JSON.stringify(UID345_object)]
];
let multi_merge_pairs = [
 ['UID234', JSON.stringify(UID234_delta)],
 ['UID345', JSON.stringify(UID345_delta)]
];

AsyncStorage.multiSet(multi_set_pairs, (err) => {
 AsyncStorage.multiMerge(multi_merge_pairs, (err) => {
   AsyncStorage.multiGet(['UID234', 'UID345'], (err, stores) => {
     stores.map((result, i, store) => {
       let key = store[i][0];
       let val = store[i][1];
       console.log(key, val);
     });
   });
 });
});

// Console log results:
// => UID234 {"name":"Chris","age":31,"traits":{"shoe_size":10,"hair":"brown","eyes":"blue"}}
// => UID345 {"name":"Marge","age":26,"traits":{"shoe_size":6,"hair":"blonde","eyes":"green"}}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Read about Batch Operating System here.

Frequently Asked Questions

What is AsyncStorage in React Native?

AsyncStorage is a simple key-value storage system that is unencrypted, asynchronous, and persistent. It enables offline data persistence in React Native apps.

Is React Native async storage safe?

No, AsyncStorage is not secure for sensitive data. AsyncStorage saves data to documents on the phone's hard drive, and therefore anyone with access to the phone's file system can read that data.

Which method is used for storing data in AsyncStorage in React Native?

setItem() is used to create new data items (where none exist) and edit existing data items.

How do you save an object in async storage react native?

Async Storage can only store string data. To store object data, you must first serialize it before storing it. For data that can be serialized to JSON, use JSON.stringify() when saving the data and JSON.parse() when loading the data.

How do I reset my async storage?

clear() removes all AsyncStorage from all clients, libraries, and other applications. To clean only your app's keys, use removeItem or multiRemove instead of using this.

Conclusion

In this blog, we learn all about AsyncStorage in React Native, its installation, storing, and fetching the data in asyncStorage. We have also discussed all the methods in async storage in detail with necessary examples.

Here is a link to the AsyncStorage module's whole API, which you can refer to for further information. You can also check this link for the usage of AsyncStorage.

If you are preparing yourself for the top tech companies, don't worry. Coding Ninjas has your back. Visit this link for a well-defined and structured material that will help you provide access to knowledge in every domain.

I hope you enjoyed reading this blog.

Live masterclass