How to Use AsyncStorage with Vega SDK

AsyncStorage is a native React Native turbo module that exposes a customer facing API in JavaScript. It supports an asynchronous API to store, update, and retrieve small string values by key in an unencrypted data store. The intent of AsyncStorage is not to store large values, like images or video, even if they are MIME encoded. For more information, please see our AsyncStorage Doc.

:white_check_mark: Sample App
This sample app shows the basic functionalities of AsyncStorage to manage local storage. The app allows users to read, write, and clear data stored on their device with simple button interactions.
Here are the key functionalities in the sample app:

  1. Store Random Messages: The app can write one of several predefined messages to the storage. This demonstrates how to store data in AsyncStorage.
  2. Read Stored Messages: The app reads and displays the last stored message from AsyncStorage. This shows how to retrieve data from AsyncStorage.
  3. Clear Storage: This functionality clears all the data stored in AsyncStorage. It’s demonstrating how to delete data from AsyncStorage.

Install the library

To install the react-native-async-storage library, follow the instructions below.

  1. Add the JavaScript library dependency in your app’s package.json.
 "dependencies": {
      ...
      "@react-native-async-storage/async-storage": "npm:@amzn/react-native-async-storage__async-storage@~2.0.0"
 },
 "overrides": {
   "@react-native-async-storage/async-storage": "npm:@amzn/react-native-async-storage__async-storage@~2.0.0"
 }
  1. Reinstall package-lock.json file using npm install command.

App.tsx Example for Vega version 0.20 and above

import React, { useState } from 'react';
import { StyleSheet, Text, TouchableOpacity, View, ScrollView } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export const App = () => {
  const key = 'HELLO';
  const [storedValue, setStoredValue] = useState('No messages read yet.');
  const [log, setLog] = useState('Start by storing or reading a message.');

  const helloMessages = [
    'Hello Kepler!',
    'Hello there, it is me :)',
    'Hello! Isn\'t it a great day?',
    'Hello! Thank you for checking out this sample app!',
  ];

  // Function to read the last stored item
  const readLastItem = async () => {
    const readValue = await AsyncStorage.getItem(key);
    if (readValue) {
      setStoredValue(`Last read message: "${readValue}"`);
      setLog(`Successfully read the message from storage.`);
    } else {
      setStoredValue('No message found in storage.');
      setLog('Attempted to read but no message was found.');
    }
  };

  // Function to write a random hello message
  const writeRandomValue = async () => {
    const randomIndex = Math.floor(Math.random() * helloMessages.length);
    const messageToStore = helloMessages[randomIndex];
    await AsyncStorage.setItem(key, messageToStore);
    setLog(`Stored: "${messageToStore}"\nNow, you can read this message.`);
  };

  // Function to clear the storage
  const clearStore = async () => {
    await AsyncStorage.clear();
    setStoredValue('No messages read yet.');
    setLog('Cleared all items from storage.\nStorage is now empty.');
  };

  return (
    <View style={styles.container}>
      <Text style={styles.titleText}>AsyncStorage Example</Text>

      <View style={styles.content}>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button} onPress={readLastItem}>
            <Text style={styles.buttonLabel}>Read from Storage</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.button} onPress={writeRandomValue}>
            <Text style={styles.buttonLabel}>Write Random Message</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.button} onPress={clearStore}>
            <Text style={styles.buttonLabel}>Clear Storage</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.messageContainer}>
          <Text style={styles.helloText}>{storedValue}</Text>
          <Text style={styles.logText}>{log}</Text>
        </View>
      </View>

      <View style={styles.footer}>
        <Text style={styles.footerTitle}>Possible Messages:</Text>
        <ScrollView style={styles.messagesList}>
          {helloMessages.map((message, index) => (
            <Text key={index} style={styles.messageItem}>{message}</Text>
          ))}
        </ScrollView>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f0f0f0',
    alignItems: 'center',
    justifyContent: 'flex-start',
    paddingTop: 30,
  },
  titleText: {
    fontSize: 40,
    fontWeight: 'bold',
    marginBottom: 100,
  },
  content: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    justifyContent: 'space-between',
    width: '100%',
    paddingHorizontal: 20,
    flex: 1,
  },
  buttonContainer: {
    width: '30%',
    justifyContent: 'space-around',
  },
  messageContainer: {
    width: '60%',
    padding: 10,
    justifyContent: 'center',
    alignItems: 'flex-start',
    flex: 1,
  },
  button: {
    backgroundColor: '#007bff',
    padding: 30,
    borderRadius: 5,
    marginBottom: 50, 
  },
  buttonLabel: {
    color: '#fff',
    fontSize: 30,
    textAlign: 'center',
  },
  helloText: {
    fontSize: 30,
    marginVertical: 40,
    padding: 40,
    backgroundColor: '#fff',
    borderColor: '#ddd',
    borderWidth: 1,
    borderRadius: 5,
    textAlign: 'left',
    width: '100%',
  },
  logText: {
    fontSize: 30,
    color: '#333',
    marginTop: 20,
    padding: 40,
    width: '100%',
    backgroundColor: '#e9ecef',
    borderRadius: 5,
    borderWidth: 1,
    borderColor: '#ddd',
    textAlign: 'left',
  },
  footer: {
    width: '100%',
    padding: 10,
    borderTopWidth: 1,
    borderTopColor: '#ddd',
    marginTop: 10,
    flex: 0.4, 
  },
  footerTitle: {
    fontSize: 30,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  messagesList: {
    marginTop: 5,
  },
  messageItem: {
    fontSize: 30,
    color: '#555',
    marginBottom: 5,
  },
});