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 the value stored at key. This will return a Promise containing a string, or null if no data has been stored yet for that key.
    • setItem(key: string, value: string) - Store the value at 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.stringify before storing data and JSON.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 at STORAGE_KEY into name using useState when it mounts. Every time you type your name in the input field and hit enter, we save name to STORAGE_KEY, as well as updating the value in name. Note that we also catch errors thrown when loading/saving.
    • Input.js, a presentational TextInput-based component
    Contents
    1. API
    2. Example

    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.

    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!