techStackGuru

React Native AsyncStorage


AsyncStorage is a key-value storage system that lets you store data persistently.

  • This is an unencrypted file, so do not store sensitive information on it.
  • As it is asynchronous, it requires promises to handle operations like saving and retrieving data.
  • Data can be accessed by all parts of your app because it is globally available.

  • Install necessary dependencies:

    npm install @react-native-async-storage/async-storage

    Example 1

    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    // Save data
    AsyncStorage.setItem('key', 'value')
      .then(() => console.log('Data saved successfully'))
      .catch((error) => console.error('Error saving data:', error));
    
    // Retrieve data
    AsyncStorage.getItem('key')
      .then((value) => console.log('Value:', value))
      .catch((error) => console.error('Error retrieving data:', error));
    
    // Remove data
    AsyncStorage.removeItem('key')
      .then(() => console.log('Data removed successfully'))
      .catch((error) => console.error('Error removing data:', error));

    Example 2

    import React, { useState, useEffect } from 'react';
    import { View, Text, TextInput, Button, AsyncStorage, StyleSheet } from 'react-native';
      
      const AsyncStorageExample = () => {
        const [inputText, setInputText] = useState('');
        const [storedData, setStoredData] = useState('');
      
        useEffect(() => {
          // Load stored data on component mount
          loadData();
        }, []);
      
        const saveData = async () => {
          try {
            // Save data to AsyncStorage
            await AsyncStorage.setItem('@MyApp:storedData', inputText);
            console.log('Data saved successfully!');
          } catch (error) {
            console.error('Error saving data:', error);
          }
        };
      
        const loadData = async () => {
          try {
            // Load data from AsyncStorage
            const data = await AsyncStorage.getItem('@MyApp:storedData');
            if (data !== null) {
              setStoredData(data);
              console.log('Data loaded successfully!');
            }
          } catch (error) {
            console.error('Error loading data:', error);
          }
        };
      
        return (
          <View style={styles.container}>
            <Text style={styles.label}>Enter text to save:</Text>
            <TextInput
              style={styles.input}
              onChangeText={(text) => setInputText(text)}
              value={inputText}
            />
            <Button title="Save" onPress={saveData} />
            <Text style={styles.label}>Stored Data:</Text>
            <Text style={styles.storedData}>{storedData}</Text>
          </View>
        );
      };
      
      const styles = StyleSheet.create({
        container: {
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
          padding: 20,
        },
        label: {
          fontSize: 16,
          marginBottom: 5,
        },
        input: {
          height: 40,
          borderColor: 'gray',
          borderWidth: 1,
          marginBottom: 10,
          padding: 10,
          width: '100%',
        },
        storedData: {
          marginTop: 10,
          fontSize: 18,
          fontWeight: 'bold',
        },
      });
      
      export default AsyncStorageExample;

    Example 3

    This example shows how to save a login token, retrieve it during app launch, and use it to log the user in automatically. Make sure your actual server-side API call and logic replaces the token validity check.

    import AsyncStorage from '@react-native-community/async-storage';
    
      const STORAGE_KEY = '@myapp:token';
      
      const storeToken = async (token) => {
        try {
          await AsyncStorage.setItem(STORAGE_KEY, token);
          console.log('Token successfully stored');
        } catch (error) {
          console.error('Error storing token:', error);
        }
      };
      
      const retrieveToken = async () => {
        try {
          const token = await AsyncStorage.getItem(STORAGE_KEY);
          return token;
        } catch (error) {
          console.error('Error retrieving token:', error);
          return null;
        }
      };
      
      const checkLogin = async () => {
        const token = await retrieveToken();
        if (token) {
          // Check token validity on your server here
          // Replace with your actual API call and logic
          const isValid = await fetch('/api/verify-token', { headers: { Authorization: `Bearer ${token}` } });
          if (isValid) {
            // Redirect to logged-in screen
            return true;
          } else {
            // Token expired, remove it and redirect to login
            await AsyncStorage.removeItem(STORAGE_KEY);
            return false;
          }
        } else {
          // No token found, redirect to login
          return false;
        }
      };
      
      export default function App() {
        const [isLoggedIn, setIsLoggedIn] = useState(false);
      
        useEffect(() => {
          async function handleLoginCheck() {
            const loggedIn = await checkLogin();
            setIsLoggedIn(loggedIn);
          }
          handleLoginCheck();
        }, []);
      
        // Render components based on isLoggedIn state
      
        if (isLoggedIn) {
          // Render logged-in user interface
        } else {
          // Render login screen
        }
      }