Open In App

React Native AsyncStorage Component

Improve
Improve
Like Article
Like
Save
Share
Report

The following approach covers how to use AsyncStorage in react-native. For this, we are going to use AsyncStorage component. AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app.

Syntax:

AsyncStorage.method();

Methods in AsyncStorage:

  • getItem(): It fetches an item for a key.
  • setItem(): It sets an item for a particular key.
  • removeItem(): It removes an item for a key.
  • mergeItem(): It merges an existing key-value with an input value.
  • clear(): It erases all AsyncStorage for all clients, libraries, etc.
  • getAllKeys(): It will get all keys known to your app.
  • flushGetRequests(): It flushes any pending requests using a single batch call to get the data.
  • multiGet(): This allows you to batch the fetching of items given an array of key inputs.
  • multiSet(): It uses this as a batch operation for storing multiple key-value pairs.
  • multiRemove(): It removes all keys from the keys array.
  • multiMerge(): It is a batch operation to merge in existing and new values for a given set of keys.

Now let’s start with the implementation:

  • Step 1: Open your terminal and install expo-cli by the following command.

    npm install -g expo-cli
  • Step 2: Now create a project by the following command.

    expo init myapp
  • Step 3: Now go into your project folder i.e. myapp

    cd myapp

Project Structure: It will look like the following.

For AsyncStorage we have AsyncStorage component in react-native, but that component is now deprecated, So in substitute for this we are going to use an external package called @react-native-async-storage/async-storage. Install that package by using the following command.

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

Example: Now let’s implement the AsyncStorage. Here we created two buttons the first button set the value and the second button fetch the value.

App.js

App.js




import React , {useState} from 'react';
import { StyleSheet, Text, View , Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
export default function App() {
  const [data , setdata] = useState("");
  const add = async ()=>{
    try {
      await AsyncStorage.setItem('gfg', "GeeksforGeeks")
    }
    catch (e){
      console.error(e);
    }
  }
  
  const get = async () => {
    try {
      const value = await AsyncStorage.getItem('gfg')
      if(value !== null) {
          setdata(value);
      }
    catch (e){
      console.error(e);
    }
  }
  return (
    <View style={styles.container}>
        <Text style={styles.text}>{data}</Text>
        <View style={styles.button} >
          <Button
            title={"add"}
            onPress={add}
          />
        </View>
        <View style={styles.button} >
          <Button
            title={"get"}
            onPress={get}
          />
        </View>
</View>
  );
}
  
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text : {
    fontSize : 40,
    marginBottom : 30
  },
  button : {
    margin:20,
    width:250
  }
});


Start the server by using the following command.

npm run android

Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. 

Reference: https://reactnative.dev/docs/asyncstorage



Last Updated : 10 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads