React Native AsyncStorage with ES 2017 Async Functions

React Native

React Native seems to have taken the mobile hybrid world by storm by breaking the confines of the Web View.

Async Storage

AsyncStorage:

AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.

Being asynchronous one has to wait for the reading or writing from AsyncStorage to complete. Otherwise, subtle bugs may arise.

Using ES217 Async Functions

One can do that asynchronous access with promises, but you will have to write the then clauses, thereby clobbering your code.

ES2017 async and await yield much simpler code:

import { AsyncStorage } from 'react-native';



// retrieve

export const retrieve = async (key) => await AsyncStorage.getItem(key);



// store

export const store = async (key, value) => {

    await AsyncStorage.setItem(key, value);

}



// store multiple keys

export const storeCredentials = async (token, permissions) => {

    await AsyncStorage.multiSet([['token', token], ['permissions', JSON.stringify(permissions)]]);

};



// clear multiple keys

export const clearCredentials = async () => await AsyncStorage.multiRemove(['token', 'permissions']);