Bird
Raised Fist0
React Nativemobile~5 mins

AsyncStorage for key-value in React Native

Choose your learning style10 modes available
Introduction

AsyncStorage lets you save small pieces of data on the phone. This helps keep information even after the app closes.

Save user preferences like theme or language
Store a login token to keep the user signed in
Remember if a tutorial was already shown
Cache small data to load faster next time
Syntax
React Native
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');
AsyncStorage methods are asynchronous and return Promises.
Always use try-catch to handle errors when reading or writing.
Examples
Save the string 'Alice' under the key 'username'.
React Native
await AsyncStorage.setItem('username', 'Alice');
Retrieve the value saved with key 'username'.
React Native
const username = await AsyncStorage.getItem('username');
Delete the saved value for 'username'.
React Native
await AsyncStorage.removeItem('username');
Sample App

This app lets you type your name and save it on the phone. When you open the app again, it shows the saved name.

React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, TextInput } 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() {
      try {
        const value = await AsyncStorage.getItem('name');
        if (value !== null) {
          setStoredName(value);
        }
      } catch (e) {
        // error reading value
      }
    }
    loadName();
  }, []);

  const saveName = async () => {
    try {
      await AsyncStorage.setItem('name', name);
      setStoredName(name);
      setName('');
    } catch (e) {
      // saving error
    }
  };

  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 }}>Saved name: {storedName}</Text> : null}
    </View>
  );
}
OutputSuccess
Important Notes

AsyncStorage is good for small data only, not big files or databases.

Always handle errors to avoid app crashes.

Data saved is persistent until removed or app is uninstalled.

Summary

AsyncStorage stores key-value pairs on the device.

Use async/await to save, read, and remove data.

Great for saving user settings and small info.

Practice

(1/5)
1. What is the main purpose of AsyncStorage in React Native?
easy
A. To create complex animations in the app
B. To handle network requests and API calls
C. To store small amounts of data as key-value pairs on the device
D. To manage app navigation between screens

Solution

  1. Step 1: Understand AsyncStorage's role

    AsyncStorage is designed to save simple data like user preferences as key-value pairs on the device.
  2. Step 2: Compare with other options

    Animations, network requests, and navigation are handled by other libraries or APIs, not AsyncStorage.
  3. Final Answer:

    To store small amounts of data as key-value pairs on the device -> Option C
  4. Quick Check:

    AsyncStorage = key-value storage [OK]
Hint: AsyncStorage saves simple data locally as key-value pairs [OK]
Common Mistakes:
  • Confusing AsyncStorage with network or UI libraries
  • Thinking AsyncStorage manages navigation or animations
2. Which of the following is the correct way to save a value using AsyncStorage in React Native?
easy
A. await AsyncStorage.setItem('key', 'value');
B. AsyncStorage.save('key', 'value');
C. AsyncStorage.store('key', 'value');
D. await AsyncStorage.put('key', 'value');

Solution

  1. Step 1: Recall AsyncStorage method for saving data

    The correct method to save data is setItem, which returns a promise and requires await.
  2. Step 2: Check method names

    Methods like save, store, and put do not exist in AsyncStorage API.
  3. Final Answer:

    await AsyncStorage.setItem('key', 'value'); -> Option A
  4. Quick Check:

    Save data = setItem [OK]
Hint: Use setItem with await to save data [OK]
Common Mistakes:
  • Using incorrect method names like save or put
  • Forgetting to use await with async calls
3. What will be logged to the console after running this code?
import AsyncStorage from '@react-native-async-storage/async-storage';

async function test() {
  await AsyncStorage.setItem('name', 'Alice');
  const value = await AsyncStorage.getItem('name');
  console.log(value);
}
test();
medium
A. Alice
B. null
C. Error: AsyncStorage not found
D. undefined

Solution

  1. Step 1: Analyze setItem and getItem usage

    The code saves the string 'Alice' under the key 'name' and then retrieves it correctly using await.
  2. Step 2: Understand console output

    Since the value was saved and retrieved successfully, console.log prints 'Alice'.
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Saved value retrieved = Alice [OK]
Hint: getItem returns saved string or null if missing [OK]
Common Mistakes:
  • Expecting undefined instead of null or string
  • Not awaiting async calls causing errors
4. Identify the error in this AsyncStorage usage:
import AsyncStorage from '@react-native-async-storage/async-storage';

function saveData() {
  AsyncStorage.setItem('token', 'abc123');
  console.log('Token saved');
}
saveData();
medium
A. console.log should be inside a .then() callback
B. Wrong method name setItem should be saveItem
C. AsyncStorage must be imported from 'react-native' not '@react-native-async-storage/async-storage'
D. Missing await before AsyncStorage.setItem causing unhandled promise

Solution

  1. Step 1: Check async usage of setItem

    AsyncStorage.setItem returns a promise and should be awaited or handled with then to ensure completion.
  2. Step 2: Identify missing await

    The function saveData is not async and does not await setItem, so the promise is unhandled and may cause issues.
  3. Final Answer:

    Missing await before AsyncStorage.setItem causing unhandled promise -> Option D
  4. Quick Check:

    AsyncStorage.setItem needs await [OK]
Hint: Always await AsyncStorage async calls to avoid unhandled promises [OK]
Common Mistakes:
  • Forgetting to make function async and use await
  • Using wrong import source
  • Incorrect method names
5. You want to remove a saved user preference with key 'theme' and then confirm it is removed. Which code snippet correctly does this?
hard
A. await AsyncStorage.clear('theme'); const val = await AsyncStorage.getItem('theme'); console.log(val);
B. await AsyncStorage.removeItem('theme'); const val = await AsyncStorage.getItem('theme'); console.log(val);
C. AsyncStorage.delete('theme'); const val = AsyncStorage.get('theme'); console.log(val);
D. AsyncStorage.remove('theme'); const val = AsyncStorage.getItem('theme'); console.log(val);

Solution

  1. Step 1: Identify correct method to remove a key

    The correct method to remove a key is removeItem, which returns a promise and should be awaited.
  2. Step 2: Confirm removal by getting the key

    After removal, calling getItem returns null, confirming deletion.
  3. Final Answer:

    await AsyncStorage.removeItem('theme'); const val = await AsyncStorage.getItem('theme'); console.log(val); -> Option B
  4. Quick Check:

    Remove key = removeItem + await [OK]
Hint: Use removeItem with await to delete keys safely [OK]
Common Mistakes:
  • Using non-existent methods like delete or remove
  • Not awaiting async calls
  • Using clear which removes all keys, not one
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard