AsyncStorage
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
CocoaPods
on iOS. See the installation instructions: https://react-native-community.github.io/async-storage/docs/install
API
The 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 thevalue
stored atkey
. This will return aPromise
containing a string, or null if no data has been stored yet for thatkey
.setItem(key: string, value: string)
- Store thevalue
atkey
, 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.stringify
before storing data andJSON.parse
after retreiving it.
Example
Let's look at an example of getting and setting a key-value pair in AsyncStorage
.
This app contains:
- An
App
component thats loads the value atSTORAGE_KEY
intoname
usinguseState
when it mounts. Every time you type your name in the input field and hit enter, we savename
toSTORAGE_KEY
, as well as updating the value inname
. Note that we also catch errors thrown when loading/saving. Input.js
, a presentationalTextInput
-based component
Want to learn React Native in-depth?
If you like React Native Express, you'll love my new book, Fullstack React Native: The complete guide to React Native! Throughout the book, we'll build 7 full apps, covering complex topics like navigation, gestures, and native modules. We don't assume any knowledge of React or newer JavaScript language features, so you can dive right in regardless of your experience level. The book comes in PDF
, EPUB
and MOBI
formats.
Community Resources
Looking for more help?
Infinite Red sponsors React Native Express and is the premier React Native agency. They're also the team behind the React Native newsletter, podcast, and conference listed here. Get in touch at infinite.red/react-native for a proposal on your next project!