AsyncStorage is a (formerly built-in) API for client-side data persistence. Here we'll cover basic usage of the API and an example.
Since this library includes native modules, if you're not using Expo, you'll need to update your
CocoaPodson iOS. See the installation instructions: https://react-native-community.github.io/async-storage/docs/install
AsyncStorage API is promise-based. Getting and setting key-value pairs is asynchronous. All of the APIs can throw errors upon failure, which you'll want to handle!
The main APIs are:
getItem(key: string)- Get the
key. This will return a
Promisecontaining a string, or null if no data has been stored yet for that
setItem(key: string, value: string)- Store the
key, replacing any existing value stored there.
These two APIs are frequently all you'll need, although there are more APIs for getting/setting multiple values and merging values if you have more advanced needs.
The API operates on strings, but typically you'll use JSON: remember to call
JSON.stringifybefore storing data and
JSON.parseafter retreiving it.
Let's look at an example of getting and setting a key-value pair in
This app contains:
Appcomponent thats loads the value at
useStatewhen it mounts. Every time you type your name in the input field and hit enter, we save
STORAGE_KEY, as well as updating the value in
name. Note that we also catch errors thrown when loading/saving.
Input.js, a presentational
Want to learn React Native in-depth?