Forem Creators and Builders 🌱

Cover image for AsyncStorage Data Storage
Samuel Guxe
Samuel Guxe

Posted on

AsyncStorage Data Storage

AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system in React Native that is global to the app. It should be used instead of LocalStorage.

It allows you to store data on the device for your app to use, which can be useful for storing small amounts of data, like user preferences or settings, and it persists even if the app is closed or the device is restarted.

Here’s a simple example of how to use AsyncStorage:

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

// Store data
const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('@storage_Key', value)
  } catch (e) {
    // saving error
  }
}

// Read data
const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, @storage_Key is the key we're using to read or write the data. You can replace it with any string that suits your needs.

Remember, AsyncStorage is not recommended for storing sensitive information, as it’s not encrypted. For sensitive data, consider using something like react-native-keychain. Also, it’s not meant for storing large amounts of data. For that, consider using a database.

Working with AsyncStorage in React Native involves storing, retrieving, and removing data. Here’s a simple example of how you can do these operations:

Import AsyncStorage
First, you need to import AsyncStorage from ‘@react-native-async-storage/async-storage’:

import AsyncStorage from '@react-native-async-storage/async-storage';
Enter fullscreen mode Exit fullscreen mode

Storing Data

You can store data with the setItem method. It takes two arguments: the key to associate with the item and the item itself.

const storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value)
await AsyncStorage.setItem('@storage_Key', jsonValue)
} catch (e) {
// saving error
}
}
Enter fullscreen mode Exit fullscreen mode

In this example, we’re storing a value with the key ‘@storage_Key’. The value is converted to a JSON string before storing.

Retrieving Data

You can retrieve data with the getItem method. It takes one argument: the key of the item you want to retrieve.

const getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('@storage_Key')
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch(e) {
// error reading value
}
}
Enter fullscreen mode Exit fullscreen mode

In this example, we’re retrieving the value associated with the key ‘@storage_Key’. The value is parsed from a JSON string back into its original format.

Removing Data

You can remove data with the removeItem method. It takes one argument: the key of the item you want to remove.

const removeData = async () => {
try {
await AsyncStorage.removeItem('@storage_Key')
} catch(e) {
// error removing value
}
}
In this example, we’re removing the value associated with the key ‘@storage_Key’.

Enter fullscreen mode Exit fullscreen mode

Remember, AsyncStorage is asynchronous, so these operations return a Promise object. That’s why we’re using the async/await syntax. Also, AsyncStorage only stores strings, so you may need to stringify your data before storing it and parse it when retrieving it.

Connecting AsyncStorage to State

Connecting AsyncStorage to your component’s state in React Native allows you to persist data across app launches and updates. Here’s an example of how you can do this:

First, import the necessary modules:

import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
Enter fullscreen mode Exit fullscreen mode

Then, create a component that uses state and AsyncStorage:

const MyComponent = () => {
  const [storedValue, setStoredValue] = useState('');

  // Function to load data from AsyncStorage
  const loadData = async () => {
    try {
      const value = await AsyncStorage.getItem('@storage_Key');
      if (value !== null) {
        setStoredValue(value);
      }
    } catch (e) {
      // error reading value
    }
  };

  // Function to save data to AsyncStorage
  const saveData = async () => {
    try {
      await AsyncStorage.setItem('@storage_Key', 'Some data');
      setStoredValue('Some data');
    } catch (e) {
      // saving error
    }
  };

  // Load any existing data in AsyncStorage when the component mounts
  useEffect(() => {
    loadData();
  }, []);

  return (
    <View>
      <Text>{storedValue}</Text>
      <Button title="Save Data" onPress={saveData} />
    </View>
  );
};

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

In this example, loadData is called when the component mounts, which sets the component's state to the value stored in AsyncStorage. The saveData function is called when the "Save Data" button is pressed, which saves a value to AsyncStorage and updates the component's state.

Remember, AsyncStorage is asynchronous, so these operations return a Promise object. That’s why we’re using the async/await syntax. Also, AsyncStorage only stores strings, so you may need to stringify your data before storing it and parse it when retrieving it.

Top comments (0)