Open In App

React Native AsyncStorage Component

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:

Now let’s start with the implementation:



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




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


Article Tags :