If you want to use another storage backend than asyncStorage, you'll still need to check that
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:
client
|- id
|_ name
room
|- id
|- number
|_ isAvailable
You have two options from this point:
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:
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.
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