Uses of async Storage in react-native

AsyncStorage is a simple yet powerful module to persist data offline in react native. We can use key-value storage system to persist the value.

Lets create a new project using expo.

expo init asyncStorageProject
cd asyncStorageProject

Lets install all the dependencies

Here, we need to have react-navigation for the navigation of the page and asyncStorage for the storing it.

expo install @react-navigation/native
expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view
expo install @react-native-async-storage/async-storage
expo install @react-navigation/stack

to start the expo server

expo start

Here, we will have 2 page.

One is the Home.js page another is the Landing.js page. On the first login, the user is asked for their name and if the user has already entered their name then they are directly navigated to their Home.js Screen. Now, lets see some code.

import React, { useState, useEffect } from "react";
import { View, Text, TextInput, StyleSheet, Button } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";

export default function Landing({ navigation }) {
  const [name, setName] = useState(null);

  const handleChangeText = async (name) => {
    setName(name);
    try {
      const value = JSON.stringify(name);
      await AsyncStorage.setItem("name", value);
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    readUser();
  }, []);

  const readUser = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem("name");
      const parseValue = JSON.parse(jsonValue);
      console.log(parseValue);
      if (parseValue) {
        navigation.navigate("Home");
      }
    } catch (e) {
      console.log(e);
    }
  };

  const handleOnPress = async () => {
    if (!name) {
      alert("Name cannot be empty");
    } else {
      try {
        const value = JSON.stringify(name);
        await AsyncStorage.setItem("name", value);
        navigation.navigate("Home");
      } catch (e) {
        console.log(e);
      }
    }
  };
  return (
    <View style={styles.container}>
      <Text style={styles.textStyle}>Please enter your name</Text>
      <TextInput
        style={styles.textInputstyle}
        onChangeText={handleChangeText}
        value={name}
      />
      <Button title="Submit" onPress={handleOnPress} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  textInputstyle: {
    width: "90%",
    height: 40,
    borderBottomWidth: 1,
  },
  textStyle: {
    fontSize: 20,
  },
});

line 1-3

We are importing all the required dependencies

In line 6

we are using useState for saving the name

In line 8-16, we have a function called handleChangeText which store the value in setState and in the try-catch block it uses AsyncStorage.setItem to persist the offline value

In line 18-20, we use useEffect react hooks to check for the name of the user with readUser(). If the user has saved their name, then it should directly navigate to Home page otherwise it should be on Landing page.

In line 22-33, we have a function as readUser, which retrieves the persist name using AsyncStorage.getItem. And if the name exists then it should navigate to Home.

In line 35-47, we have a function called handleOnPress which is called by pressing on Submit Button on line 56.

Conclusion

I have published the code in Github repo

https://github.com/TriptiPant01/asynstorageRepo