0
0
React-nativeHow-ToBeginner ยท 4 min read

How to Use Async Storage in React Native: Simple Guide

Use @react-native-async-storage/async-storage to store and retrieve data asynchronously in React Native. Import it, then use setItem to save and getItem to read data in async functions.
๐Ÿ“

Syntax

Async Storage provides simple methods to save and load data asynchronously. The main methods are:

  • setItem(key, value): Saves a string value under a key.
  • getItem(key): Retrieves the string value for a key.
  • removeItem(key): Deletes the value for a key.

All methods return promises, so use async/await to handle them.

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

// Save data
await AsyncStorage.setItem('key', 'value');

// Read data
const value = await AsyncStorage.getItem('key');

// Remove data
await AsyncStorage.removeItem('key');
๐Ÿ’ป

Example

This example shows a simple React Native component that saves a username to Async Storage and loads it when the app starts.

javascript
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function App() {
  const [name, setName] = useState('');
  const [storedName, setStoredName] = useState('');

  useEffect(() => {
    async function loadName() {
      const savedName = await AsyncStorage.getItem('username');
      if (savedName) setStoredName(savedName);
    }
    loadName();
  }, []);

  async function saveName() {
    await AsyncStorage.setItem('username', name);
    setStoredName(name);
    setName('');
  }

  return (
    <View style={{ padding: 20 }}>
      <Text>Enter your name:</Text>
      <TextInput
        value={name}
        onChangeText={setName}
        placeholder="Your name"
        style={{ borderWidth: 1, marginVertical: 10, padding: 5 }}
      />
      <Button title="Save Name" onPress={saveName} />
      {storedName ? <Text style={{ marginTop: 20 }}>Stored name: {storedName}</Text> : null}
    </View>
  );
}
Output
UI with a text input, a button, and text showing the stored name after saving.
โš ๏ธ

Common Pitfalls

Common mistakes when using Async Storage include:

  • Not awaiting setItem or getItem, causing race conditions.
  • Storing non-string data without converting it to string (use JSON.stringify and JSON.parse).
  • Ignoring errors from Async Storage methods.
  • Using Async Storage for large or sensitive data (it is meant for small, simple data).
javascript
import AsyncStorage from '@react-native-async-storage/async-storage';

// Wrong: storing object directly
const user = { id: 1, name: 'Alice' };
// await AsyncStorage.setItem('user', user); // This will fail

// Right: convert object to string
await AsyncStorage.setItem('user', JSON.stringify(user));

// When reading:
const userString = await AsyncStorage.getItem('user');
const userObj = userString ? JSON.parse(userString) : null;
๐Ÿ“Š

Quick Reference

Here is a quick summary of Async Storage methods:

MethodDescription
setItem(key, value)Save a string value under the key.
getItem(key)Retrieve the string value for the key.
removeItem(key)Delete the value for the key.
clear()Remove all keys and values.
getAllKeys()Get an array of all keys stored.
โœ…

Key Takeaways

Always import Async Storage from '@react-native-async-storage/async-storage' to use it.
Use async/await with setItem and getItem to handle data storage and retrieval.
Convert objects to strings with JSON.stringify before saving and parse them after loading.
Handle errors and avoid storing large or sensitive data in Async Storage.
Use Async Storage for simple, small pieces of data like user preferences or tokens.