react-native
  1. react-native-asyncstorage-methods

React-Native AsyncStorage Methods

Syntax

The React-Native AsyncStorage API provides methods for storing and retrieving data from the device's local storage:

import AsyncStorage from '@react-native-async-storage/async-storage';

AsyncStorage.setItem('key', 'value');
AsyncStorage.getItem('key');

Example

import AsyncStorage from '@react-native-async-storage/async-storage';

const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('myKey', value)
  } catch (e) {
    console.log(e)
  }
}

const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('myKey')
    if(value !== null) {
      console.log(value)
    }
  } catch(e) {
    console.log(e)
  }
}

Output

If the storeData function successfully stores the string "Hello, World!" in async storage under the key myKey, and the getData function successfully retrieves the stored value, the following message will be logged to the console:

Hello, World!

Explanation

AsyncStorage is a simple, asynchronous key-value store for storing persistent data on a mobile device. It allows data to be stored even after the app is closed or the device is restarted.

The AsyncStorage API includes a variety of methods for storing and retrieving data, including:

  • setItem(key, value): Stores the specified value under the provided key.
  • getItem(key): Retrieves the value stored under the provided key.
  • removeItem(key): Removes the item stored under the provided key.
  • getAllKeys(): Retrieves an array of all keys stored in the AsyncStorage.
  • clear(): Removes all items stored in the AsyncStorage.

Use

AsyncStorage is commonly used for storing user preferences, authentication tokens, and other settings that need to persist beyond the lifetime of a single app session.

Data stored in AsyncStorage can be retrieved and used across multiple components within a React-Native app.

Important Points

  • AsyncStorage data is stored as a string, so complex data structures must be stringified before storage and parsed when retrieved.
  • AsyncStorage is not encrypted, so sensitive data should not be stored using this API.
  • AsyncStorage has a limited storage capacity, so it should only be used for small amounts of data.
  • AsyncStorage supports both iOS and Android devices.

Summary

AsyncStorage is a useful API for storing and retrieving small amounts of persistent data in a React-Native app. By providing simple methods for key-value storage, AsyncStorage helps to simplify the process of data management in mobile apps.

Published on: