Remember Me Functionality In React-Native with asyncstorage

Kushal chapagain || 9/10/2024

The basic concept behind the remember me functionality is store the information on local storage and retrieve from local storage. In this case we use asyncstorage as our local storage to store user information ,in the blog we will remember the user email .

first we create the simple login form with field email and Password , one remember me checkbox and submit button loginPage.js .

For checkbox I use checkbox from the react native community ,to install it just run npm i @react-native-community/checkbox .

import CheckBox from '@react-native-community/checkbox'; import React, {useState} from 'react'; import {Text, TextInput, TouchableOpacity, View} from 'react-native'; const SigninForm = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [rememberMe, setRememberMe] = useState(false); const handleSignIn = () => {}; return ( <View className="flex-1 items-center justify-center"> <TextInput className="bg-gray-50 border w-80 mb-3 border-gray-300 text-gray-900 text-sm rounded-lg px-3" placeholder="Email" placeholderTextColor={'gray'} onChangeText={text => setEmail(text)} value={email} /> <TextInput className="bg-gray-50 border w-80 mb-3 border-gray-300 text-gray-900 text-sm rounded-lg px-3" placeholder="Password" placeholderTextColor={'gray'} secureTextEntry={true} onChangeText={text => setPassword(text)} value={password} /> <View className="items-center flex-row my-2"> <CheckBox value={rememberMe} tintColors={{true: 'purple', false: 'gray'}} onValueChange={newValue => setRememberMe(newValue)} /> <Text className="text-black font-semibold text-lg">Remember Me</Text> </View> <TouchableOpacity className="py-2 px-6 bg-purple-600 rounded-full" onPress={handleSignIn}> <Text className="text-white font-bold text-xl">Sign In</Text> </TouchableOpacity> </View> ); }; export default SigninForm;

there will be some minor adjustment on the code later in order to integrate remember me functionality and I use naitvewind for the styling.

After creating form let’s create the functions that stores and retrieve the email to/from the asyncstorage. To do so first you need to install asyncstorage and rebuild you app, to install asyncstorage type npm i @react-native-async-storage/async-storage

Make a component which have functions to store and get the data form asyncstorage in our case it’s email and the status of check box.

import AsyncStorage from '@react-native-async-storage/async-storage'; const storeUserEmail = async email => { try { await AsyncStorage.setItem('email', JSON.stringify(email)); console.log('email stored for remember me'); } catch (error) { console.error('Error storing email for remembre me:', error); } }; const getUserEmail = async () => { try { const emailValue = JSON.parse(await AsyncStorage.getItem('email')); console.log('getting email for the remember me', emailValue); return emailValue !== null ? {emailValue} : {emailValue: ''}; } catch (error) { console.error('Error getting stored email fo rmemerme:', error); return null; } }; const clearUserEmail = async () => { try { await AsyncStorage.removeItem('email'); console.log('Email cleared from AsyncStorage'); } catch (error) { console.error('Error clearing email from AsyncStorage:', error); } }; const storeCheckStatus = async value => { try { await AsyncStorage.setItem('checkStatus', JSON.stringify(value)); console.log('check value stored for remember me'); } catch (error) { console.error('Error storing check value for remember me:', error); } }; const getCheckStatus = async () => { try { const checkValue = JSON.parse(await AsyncStorage.getItem('checkStatus')); console.log('getting check value for remember me:', checkValue); return checkValue !== null ? {checkValue} : {checkValue: false}; } catch (error) { console.error('Error getting check value for remember me:', error); return null; } }; export { clearUserEmail, getCheckStatus, getUserEmail, storeCheckStatus, storeUserEmail, };

In your main login page file write the logic which will store the checkbox status (true or false) on checkbox click and store email value in asyncstorage on login button press.

const handleCheckboxPress = async () => { setChecked(!checked); await storeCheckStatus(!checked); }; const handleSignIn = () => { navigation.navigate('tabnavigation') storeUserEmail(initialEmail); };

To get the status of checkbox and email value you need to get the value when component mount so we use uesEffect to get the value form asyscstorage.

useEffect(() => { const fetchValuesFormStorage = async () => { try { const {emailValue} = await getUserEmail(); const {checkValue} = await getCheckStatus(); console.log('got status value:', checkValue); console.log('got email value:', emailValue); setChecked(checkValue); setInitialEmail(emailValue); setEmailLoaded(true); if (!checkValue) { clearUserEmail(); } } catch (error) { console.error('Error fetching checkValue or email:', error); } }; fetchValuesFormStorage(); }, []);

Here we set setEmailLoaded(true) on component mount to conform the email is loaded from asyncstorage before form load so that we can set the email value to the value from asyncstorage value.

After the set the condition if checkstatus is true set the initial email as email from the asyncstorage and if the checkstatus is false set the initial email as blank.

Here is the full code of SigninPage.js

import CheckBox from '@react-native-community/checkbox'; import React, {useEffect, useState} from 'react'; import {Text, TextInput, TouchableOpacity, View} from 'react-native'; import { clearUserEmail, getCheckStatus, getUserEmail, storeCheckStatus, storeUserEmail, } from '../components/StoreAndGetRememberMe'; import { useNavigation } from '@react-navigation/native'; const SigninForm = () => { const navigation=useNavigation() const [email, setEmail] = useState(''); const [initialEmail, setInitialEmail] = useState(); const [password, setPassword] = useState(''); const [emailLoaded, setEmailLoaded] = useState(false); const [checked, setChecked] = useState(); useEffect(() => { const fetchValuesFormStorage = async () => { try { const {emailValue} = await getUserEmail(); const {checkValue} = await getCheckStatus(); console.log('got status value:', checkValue); console.log('got email value:', emailValue); setChecked(checkValue); setInitialEmail(emailValue); setEmailLoaded(true); if (!checkValue) { clearUserEmail(); } } catch (error) { console.error('Error fetching checkValue or email:', error); } }; fetchValuesFormStorage(); }, []); const handleCheckboxPress = async () => { setChecked(!checked); await storeCheckStatus(!checked); }; const handleSignIn = () => { navigation.navigate('tabnavigation') storeUserEmail(initialEmail); }; return ( emailLoaded && ( <View className="flex-1 items-center justify-center"> <TextInput className="bg-gray-50 border w-80 mb-3 border-gray-300 text-gray-900 text-sm rounded-lg px-3" placeholder="Email" placeholderTextColor={'gray'} onChangeText={text => setInitialEmail(text)} value={checked ? initialEmail : null} /> <TextInput className="bg-gray-50 border w-80 mb-3 border-gray-300 text-gray-900 text-sm rounded-lg px-3" placeholder="Password" placeholderTextColor={'gray'} secureTextEntry={true} onChangeText={text => setPassword(text)} value={password} /> <View className="items-center flex-row my-2"> <CheckBox value={checked ? true : false} tintColors={{true: 'purple', false: 'gray'}} onValueChange={handleCheckboxPress} /> <Text className="text-black font-semibold text-lg">Remember Me</Text> </View> <TouchableOpacity className="py-2 px-6 bg-purple-600 rounded-full" onPress={handleSignIn}> <Text className="text-white font-bold text-xl">Sign In</Text> </TouchableOpacity> </View> ) ); }; export default SigninForm;

Thank you! Happy Learning.