Various methods in async storage react native

29 Aug 2022
Intermediate
2.75K Views
19 min read  

AsyncStorage is recognized as an asynchronous, unencrypted, constant, key-value storage system. It is global to the app. Moreover, it must be used instead of LocalStorage. Instead of directly using AsyncStorage, it is recommended to use an abstraction on top of AsyncStorage for average or heavy usage. The reason is it operates worldwide.

On iOS, the AsyncStorage is supported by native code which saves the corresponding small values within a sequential dictionary and bigger values in separate files. But on Android, AsyncStorage either uses SQLite or RocksDB depending on the availability.

There are some specific scenarios where the AsyncStorgae module can be beneficial. Persisting the application data in a mobile app can have certain benefits such as when the user restarts the app abruptly, then the last active data or the internal setting variables should be available to the user in the state they left before closing the app unexpectedly so for that situation we should have some global and async storage where we can have a key-value pair structure which can be persisted across the session.

When you attend React js Certification, you will come across different methods of AsyncStorage.

Now let’s discuss various methods in Async Storage React Native:

Methods:

getItem():

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

This method fetches an item for a key and requests a callback after completion. It returns a Promise object.

The ‘key’ parameter is required and it represents the key of the item to be fetched. Its type is a string.

The ‘callback’ parameter is not required. It represents a function that will be called with a result when found or any error.

setItem():

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

It sets the value for a particular key and requests a callback after completion. It returns a Promise object. Once you go through the React tutorial, you will know in detail about this method including other methods as well.

The ‘key’ parameter is required and it shows the key of the item whose value you wish to set. Its type is a string.

The ‘value’ parameter is required and it shows the value to be set for the particular key. Its type is a string.

The ‘callback’ parameter is not required. It shows the function which will be called with an error.

removeItem():

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

This method in Async Storage React Native discards an item for a particular key. Also, it requests a callback after completion. Moreover, it returns a Promise object.

In this method, 2 parameters are included i.e. key and callback.

The ‘key’ parameter is required as shows the key of the item which you want to discard. Its type is a string.

The ‘callback’ parameter is not compulsory to include. It highlights the function which will be called with an error.

clear():

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

This method erases out every AsyncStorage for all libraries, clients, etc. It is infrequently called upon. You can use multiRemove or removeItem to clear out only the keys of your app. Furthermore, it returns a Promise object.

Its parameter is a callback which is not always required. This parameter includes a function that would be called with an error.

mergeItem():

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

It merges an input value with an existing key value. During this, it assumes that both values are stringified JSON. Moreover, it returns a Promise object.

3 parameters it covers are ‘key’, ‘value’, and ‘callback’. The ‘key’ and ‘value’ are required whereas ‘callback’ is optional. The ‘key’ parameter is a string type and it shows the key of the item which you want to modify. The ‘value’ parameter is a string type and it shows a new value to be merged for the key. The third parameter i.e. callback depicts that a function that will be invoked with an error.

flushGetRequests():

static flushGetRequests(): [object Object]

It flushes out any pending requests through a single batch call to receive the data.

getAllKeys():

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

With this method, you receive all keys that are known to your app. It works for all libraries, callers, etc. The react learning path discusses this method that explains how you can obtain all keys.

The only parameter it uses is ‘callback’ which includes a function that will be called with every key found and any error.

multiGet():

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

This method packs the fetching of items based on an array of key inputs. Your call request will be employed with an array of equivalent key-value pairs being found. For example, the following command packs the k1 and k2 items depending on the key inputs i.e. val1 and val2.

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

2 parameters it covers are ‘keys’ and ‘callback’. The ‘keys’ parameter is required and it shows an array of keys for the items to obtain. Another parameter i.e. ‘callback’ represents a function that would be called with a key-value array of the results. Additionally, it represents an array of any key-specific errors being found. Keep in mind that this parameter is optional.

multiSet():

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

multiSet() is used as a batch operation for the storage of multiple key-value pairs. Once the operation finishes, you would receive a single callback with errors (if any). A Promise object is returned by this method.

It comes with 2 parameters i.e. ‘keyValuePairs’ and ‘callback’. The first one is mandatory and it shows an array of key-value for the items to be set. The ‘callback’ parameter represents a function that would be called with an array of key-specific errors detected.

multiRemove():

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

This method can be invoked to delete all keys within the keys array. 

Names of parameters it includes are ‘keys’ and ‘callback’. The type of ‘keys’ is array<string>. It depicts the array of keys for the items to be deleted. On the other hand, the ‘callback’ parameter is optional and it includes a function that will be invoked an array of key-specific errors being detected.

multiMerge():

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

This method implements the batch operations to merge in the old as well as new values for a provided set of keys. It is assumed that the values are stringified JSON.  Keep in mind that this method is not supported by every native implementation.

The names of its two parameters are ‘keyValuePairs’ and ‘callback’. The first one is required and it describes a key-value array for those items to be merged. In the ‘callback’ parameter, the function will be invoked with an array of any of the key-specific errors being detected.

Note:

As per the official documentation of the react-native, the AsyncStorage has been deprecated which means no future changes or maintenance will be available, but we can opt for the additional package available for using such async storage which is given below.

  1. @react-native-async-storage/async-storage
  2. typed-async-storage
  3. react-native-storage
  4. react-native-encrypted-storage
  5. react-native-sqlite-storage
  6. react-native-mmkv

Using any of the above or other packages will allow us to use async storage event efficient than the existing storage mechanism so try out accordingly

Share Article
About Author
Amit Kumar (Software Engineer And Author)

Experienced Software Engineer with a demonstrated history of working in the professional training & coaching industry. Skilled in Asp.net MVC, Angular, Language Integrated Query (LINQ), SQL, C++, and HTML. Strong engineering professional graduated from Sathyabama University.
Learn to Crack Your Technical Interview
Accept cookies & close this