asyncstorage.mo

Control Points

Motivation

  • You want some data to be persisted accross application restart.

Prerequisites

We need to import AsyncStorage from react-native.

The following example will use three simple methods:

  • AsyncStorage.setItem(key, value)

  • AsyncStorage.getItem(key)

  • AsyncStorage.removeItem(key)

key and value are two strings, so don't pass a Javascript object in these functions! All AsyncStorage methods return a Promise object.

Steps (~15 minutes)

It is recommended to use an extra layer of abstraction on top of the bare AsyncStorage that takes into account the particularities of the data you want to store. Let's start with a simple example where the hotel bookings I want to store have this structure:

roomId and clientId refer to the following objects:

You have two options from this point:

  1. Storing simple values

In this example, we want to display basic info about a current booking, such as bookingDate, clientName, and roomNumber. Let's first define a extra layer to list our AsyncStorage keys, in a myAsyncStorage.js file for example:

These keys can be used to save/fetch data on the device in a bookings.js MobX store:

This approach works fine until you want to preload data in the form of objects and not strings. e.g. multiple bookings. Fortunately there is a workaround to solve this issue.

  1. Storing complex objects in JSON strings

We mentioned earlier that you shouldn't pass anything else than a string to AsyncStorage.setItem. You can however use JSON.stringify to convert your JavaScript objects to serialized JSON strings for storage. The original objects can be recovered using the JSON.parse method. Our myAsyncStorage.js file becomes:

Notice how the file has become more manageable and easy to read. To manage the conversion between Javascript objects and the strings that AsyncStorage receives, it is recommended to define a couple of getter/setter helper functions. You will avoid systematically calling JSON.parse and JSON.stringify outside myAsyncStorage.js, keeping your code even more readable:

Notice that by using Promise rejection in the getObjectFromAsyncStorage method, we can avoid checking whether loaded items are empty, thus refactoring our code.

Troubleshooting and extras

There are of course many more ways to use asyncStorage, if you want to explore them visit this page

Last updated