React Native AsyncStorage
This is an Example to Store Data in Session Using AsyncStorage in React Native. React Native AsyncStorage
can be used to manage sessions.
If you want the user to log in once and don’t want to log in again when the user opens the app after some time then, you have to store any variable in the app which can be checked and according to that, we will show the screen.
For example, once we login we can store the user id in the AsyncStorage to remember the user and when we open the app again we check for the user id, If it is there in the AsyncStorage then we can directly send the user to the next screen without login else we will show the Login Screen. This process is called session management using AsyncStorage.
AsyncStorage can only be used to store small values in the form of a key and value pair because it has some limitations to store the data. You can store your value with respect to any key and then can access the value using the key again. It works perfectly on both platforms (Android and IOS).
To Import AsyncStorage in Code
import AsyncStorage from '@react-native-async-storage/async-storage'
Store the value in AsyncStorage
AsyncStorage.setItem('any_key_here', this.state.textInputData);
Get the value from the AsyncStorage
AsyncStorage.getItem('any_key_here').then(value =>
//AsyncStorage returns a promise so adding a callback to get the value
this.setState({ getValue: value })
//Setting the value in Text
);
In this Example. We will see the use of AsyncStorage by storing some value and after that, we will retrieve the value from the same key. So let’s get started.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency
To use AsyncStorage
we need to install @react-native-async-storage/async-storage
dependency.
To install this open the terminal and jump into your project using
cd ProjectName
Run the following command to install
npm install @react-native-async-storage/async-storage --save
This command will copy all the dependency into your node_module directory. –save is optional, it is just to update the @react-native-community/async-storage dependency in your package.json file.
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install
Code
Now, Open App.js in any code editor and replace the code with the following code
App.js
// AsyncStorage in React Native to Store Data in Session
// https://aboutreact.com/react-native-asyncstorage/
// import React in our code
import React, {useState} from 'react';
// import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
View,
TextInput,
Text,
TouchableOpacity,
} from 'react-native';
// import AsyncStorage
import AsyncStorage from '@react-native-async-storage/async-storage';
const App = () => {
// To get the value from the TextInput
const [textInputValue, setTextInputValue] = useState('');
// To set the value on Text
const [getValue, setGetValue] = useState('');
const saveValueFunction = () => {
// Function to save the value in AsyncStorage
if (textInputValue) {
// To check the input not empty
AsyncStorage.setItem('any_key_here', textInputValue);
// Setting a data to a AsyncStorage with respect to a key
setTextInputValue('');
// Resetting the TextInput
alert('Data Saved');
// Alert to confirm
} else {
alert('Please fill data');
}
};
const getValueFunction = () => {
// Function to get the value from AsyncStorage
AsyncStorage.getItem('any_key_here').then(
(value) =>
// AsyncStorage returns a promise
// Adding a callback to get the value
setGetValue(value),
// Setting the value in Text
);
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Text style={styles.titleText}>
AsyncStorage in React Native to Store Data in Session
</Text>
<TextInput
placeholder="Enter Some Text here"
value={textInputValue}
onChangeText={(data) => setTextInputValue(data)}
underlineColorAndroid="transparent"
style={styles.textInputStyle}
/>
<TouchableOpacity
onPress={saveValueFunction}
style={styles.buttonStyle}>
<Text style={styles.buttonTextStyle}>
SAVE VALUE
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={getValueFunction}
style={styles.buttonStyle}>
<Text style={styles.buttonTextStyle}>
GET VALUE
</Text>
</TouchableOpacity>
<Text style={styles.textStyle}>
{getValue}
</Text>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
backgroundColor: 'white',
},
titleText: {
fontSize: 22,
fontWeight: 'bold',
textAlign: 'center',
paddingVertical: 20,
},
textStyle: {
padding: 10,
textAlign: 'center',
},
buttonStyle: {
fontSize: 16,
color: 'white',
backgroundColor: 'green',
padding: 5,
marginTop: 32,
minWidth: 250,
},
buttonTextStyle: {
padding: 5,
color: 'white',
textAlign: 'center',
},
textInputStyle: {
textAlign: 'center',
height: 40,
width: '100%',
borderWidth: 1,
borderColor: 'green',
},
});
export default App;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
That was the React Native AsyncStorage. If you have any doubts or want to share something about the topic you can comment below or contact us here. The remaining components will be covered in the next article. Stay tuned!
Hope you liked it. 🙂