In this tutorial we will learn how to store user data into session using session plugin. Async Storage in React Native is used to store the user data into session. In this tutorial we will store the data into session.
Async Storage is now Deprecated . Use another library like community packages.
But don’t worry we will use Async Storage Library To Store the Data. There are lot of library for storing the data into session. Run the following command in terminal to install the Async Storage Session Library in React Native Project.
npm for Async Storage React Native Projects
npm install @react-native-async-storage/async-storage
yarn add @react-native-async-storage/async-storage
expo install @react-native-async-storage/async-storage
After installing the dependency follow the below step which is must to do in the terminal.
cd ios – > pod install
Pod install imports the added dependency to the exiting project. After that you can return to the main directory by running the following command in terminal.
cd – > cd desktop – > cd your_project_name
Import The Package
Import the following package to the entire component or the class to use Async Storage Session In React Native.
import AsyncStorage from '@react-native-async-storage/async-storage';
How to Store User Data in Session In React Native
You can store the data using the following steps.
Getting the Session Values From Async Storage in React Native
To get the values from the Async Storage use following statements.
How To Remove The Session Values From Async Storage In React Native.
To remove the session values from async storage use the seItem empty. You can follow us as below to remove the session values.
Example To Store The user Data In Session
In this example we will store the user data after login successful and remove on the logout button click. Use key and value pair to store the data.
AsyncStorage.setItem("isLogin", "true"); AsyncStorage.setItem("userId", this.state.userName); AsyncStorage.setItem("password", this.state.password);
Getting the Session values from Session in React Native
To get the values from the session in react native use the getItem inbuilt method. You can get the above session value as below using the key name.
AsyncStorage.getItem("isLogin"); AsyncStorage.getItem("userId"); AsyncStorage.getItem("password");
Remove the Session Values
To remove the session values from above session use the following statements. Use the following code for logout the session.
AsyncStorage.setItem("isLogin", "false"); AsyncStorage.setItem("userId", ""); AsyncStorage.setItem("password", "");
Thank you for visiting this tutorial. Hope this help you to learn something.