import React, {FC, useCallback, useContext, useEffect, useState} from "react"; import {…
- User
import React, {FC, useCallback, useContext, useEffect, useState} from "react"; import { Image, ImageBackground, Keyboard, Platform, SafeAreaView, ScrollView, StatusBar, View, } from "react-native";
import {useHeaderHeight} from "@react-navigation/elements"; import {useFocusEffect} from "@react-navigation/native"; import {StackNavigationProp} from "@react-navigation/stack"; import DeviceInfo from "react-native-device-info"; import KeyChain from "react-native-keychain";
import Alert from "@components/alert"; import Background from "@components/background"; import BiometricAlert from "@components/biometricAlert"; import Card from "@components/card"; import Divider from "@components/divider"; import TextInput from "@components/input"; import Button from "@components/primaryButton"; import SecondaryButton from "@components/secondaryButton";
import {apiServerMessages} from "@config/constants/APIMessagesConstants"; import {IS_DEVICE_REGISTERED_TO_PUSH_NOTIFICATION} from "@config/constants/AppConstants"; import {keyChainICServers} from "@config/constants/AuthConstants"; import { defaultErrorDescription, defaultErrorTitle, } from "@config/constants/ErrorMsgConstants"; import { AppState, Platforms, } from "@config/constants/GenericReactNativeConstants"; import {AuthNavigatorParamList} from "@config/constants/NavConstants"; import {translationKeys} from "@config/constants/TranslationConstants"; import {getLocalizationContext} from "@config/Translations"; import {iStateMessage} from "@config/types/GenericReduxTypes"; import {httpStatusCodes} from "@config/types/NetworkTypes"; import { ButtonOnPressType, TextInputOnChangeTextType, } from "@config/types/ReactNativeTypes"; import useAppState from "@hooks/appStateListener"; import useKeyboard from "@hooks/keyboardListener"; import useIsNetworkReachable from "@hooks/networkStatusListener"; import RootScreen from "@screens/rootScreen"; import localStorage from "@services/asyncStorage"; import getFCMToken from "@services/firebase/fcm"; import { resetAuthState, updateAuthPersistState, updateManualLoginStatus, } from "@store/auth/AuthSlice"; import * as authThunkActions from "@store/auth/ThunkActions"; import {fetchDealerLocationInformation} from "@store/dealerServices/ThunkAction"; import {useAppDispatch, useAppSelector} from "@store/Hooks"; import { hideLoader as hideFanLoader, showLoader as showFanLoader, } from "@store/loader/LoaderSlice"; import {resetLocationState} from "@store/location/LocationSlice"; import * as userThunkActions from "@store/user/ThunkActions";
import { getCurrentTheme, getSystemTheme, useThemeAwareObject, } from "@styles/theming/ThemingHelper"; import AppUtil from "@utils/AppUtil"; import {validateEmail, validatePassword} from "@utils/InputValidationUtil"; import {turnOffAllNotifications} from "@utils/PushNotificationsUtil";
import BiometricView from "./components/BiometricView"; import Styles from "./Styles"; import {getBackgroundImage, getLogo} from "./Utils";
type LoginScreenNavigationProp = StackNavigationProp< AuthNavigatorParamList, "LoginScreen"
;
type Props = { navigation: LoginScreenNavigationProp; };
const LoginScreen: FC = ({navigation}: Props) => { /** Initializers */ const styles = useThemeAwareObject(Styles.createStyles); const {translate} = useContext(getLocalizationContext());
const isKeyBoardOpen = useKeyboard(); const dispatch = useAppDispatch(); const settingsState = useAppSelector((state) => { return state.settingsReducer; }); const networkStatus = useIsNetworkReachable(); const appState = useAppState(); const [themeId, setThemeId] = useState<string>(getSystemTheme().themeId); /** State variables */ const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isLoginCredentialsPresent, setIsLoginCredentialsPresent] = useState< boolean | null >(null); const [isAlertVisible, setIsAlertVisible] = useState(false); const [alertStatus, setAlertStatus] = useState<{ isVisible: boolean; title: string; message: string; onPress: Function | null; buttonTitle: string; }>({ isVisible: false, title: translate(defaultErrorTitle), message: "", onPress: null, buttonTitle: translate(translationKeys.alertButtonTitle.capsOk), }); /** * Need to add this when view comes into focus - * as on android when any back navigation event happens UI is not updating properly if this is only mentioned in render * Hence need it at focus level and render level. */ useFocusEffect( useCallback(() => { StatusBar.setBarStyle("dark-content"); if (Platform.OS === Platforms.android) { StatusBar.setTranslucent(true); StatusBar.setBackgroundColor("transparent"); } }, []), ); useEffect(() => { (async () => { if (appState === AppState.active) { const theme = await getCurrentTheme(); setThemeId(theme.themeId); } })(); }, [styles.statusbar.backgroundColor, appState]); /** * Function which shows or hide loader based on boolean value passed * * @param loading */ const showLoader = (loading: boolean) => { if (navigation.isFocused()) { if (loading) { dispatch(showFanLoader()); } else { dispatch(hideFanLoader({className: "LoginScreen"})); } } }; /** Custom functions */ const onNavigate = async () => { /* Dispatch api to fetch location information to get to know if dealer services alert is to be shown. // */ dispatch(userThunkActions.getUserDetails()); dispatch(fetchDealerLocationInformation()); await dispatch(updateAuthPersistState()); }; const onChangeTextEmail: TextInputOnChangeTextType = (id, text) => { setEmail(text); }; const onChangeTextPassword: TextInputOnChangeTextType = (id, text) => { setPassword(text); }; const onCallback = (isCredentialsPresent: boolean) => { setIsLoginCredentialsPresent(isCredentialsPresent); }; const onDismissAlert = () => { setAlertStatus({ isVisible: false, title: alertStatus.title, message: alertStatus.message, onPress: null, buttonTitle: alertStatus.buttonTitle, }); }; const showAlert = ( message: string, title: string, buttonTitle: string, onPress: Function | null = null, ) => { showLoader(false); setAlertStatus({ isVisible: appState === AppState.active, title, message, onPress, buttonTitle, }); }; const onNavigateToConfirmScreen = async (email: string) => { showLoader(true); const resendResponse = await dispatch( userThunkActions.resendOtpForAccountCreation({ email, }), ); if (resendResponse.meta.requestStatus === "fulfilled") { showLoader(false); navigation.navigate("ConfirmAccountScreen", { email, password, }); } else { const {message, httpStatusCode} = resendResponse.payload as iStateMessage; showLoader(false); if (httpStatusCode !== httpStatusCodes.NO_INTERNET) { showAlert( message as string, translate(defaultErrorTitle), translate(translationKeys.alertButtonTitle.capsOk), ); } } }; /** Registers user for push notification */ const registerDeviceForNotification = async ( email: string, ): Promise<boolean> => { try { const fcmToken = await getFCMToken(); if (fcmToken) { const appUUID = await AppUtil.getAppUUID(); await dispatch( userThunkActions.registerDeviceForNotification({ deviceInfo: { email, device_id: appUUID, device_token: fcmToken, device_type: Platform.OS, brand: AppUtil.getAppBrandName(), }, }), ).unwrap(); return true; } return false; } catch (error) { return false; } }; /** Gets login and user details */ const getLoginCredentials = async ( email: string, password: string, ): Promise<{ status: boolean; httpStatusCode?: httpStatusCodes | null | undefined; messageId: string | null | undefined; title?: string | null | undefined; message: any; }> => { const loginDetails = await dispatch( authThunkActions.authenticate({email, password}), ); /** We are going with old approach of checking for request status rather that hooks as it was having some side effects */ if (loginDetails.meta.requestStatus === "fulfilled") { /** * Fetching user details if login is successful * TODO: See if we can move this logic to a service file and call that in login thunk rather at screen level */ const userDetails = await dispatch(userThunkActions.getUserDetails()); if (userDetails.meta.requestStatus === "fulfilled") { /** If user details are fetched successfully register device for receiving notification */ const isRegistered = await registerDeviceForNotification(email.trim()); showLoader(false); setIsAlertVisible(true); if (isRegistered) { /** If device is registered set local storage to true */ localStorage.setItem(IS_DEVICE_REGISTERED_TO_PUSH_NOTIFICATION, true); } else { /** otherwise turn all notification preferences to off */ turnOffAllNotifications(email.trim()); } /* Dispatch api to fetch location information to get to know if dealer services alert is to be shown. */ dispatch(updateManualLoginStatus({isManualLogin: true})); dispatch(fetchDealerLocationInformation()); return { status: true, messageId: null, message: "success", }; } const errorMessage = userDetails.payload as iStateMessage; return { status: false, httpStatusCode: errorMessage.httpStatusCode, messageId: errorMessage.messageId, title: errorMessage.title, message: errorMessage.message, }; } const errorMessage = loginDetails.payload as iStateMessage; return { status: false, httpStatusCode: errorMessage.httpStatusCode, messageId: errorMessage.messageId, title: errorMessage.title, message: errorMessage.message, }; }; const onLoginResponse = ( email: string, response: { status: boolean; httpStatusCode?: httpStatusCodes | null | undefined; messageId: string | null | undefined; title?: string | null | undefined; message: any; }, ) => { // Checks // 1. USER_NOT_CONFIRMED_EXCEPTION // 2. BRAND_EXCEPTION_ERROR // 2. Show alert for generic error if ( !response.status && response.messageId === apiServerMessages.errors.USER_NOT_CONFIRMED_EXCEPTION ) { onNavigateToConfirmScreen(email); } else if (!response.status) { showAlert( translate(response.message || defaultErrorDescription), translate(defaultErrorTitle), translate(translationKeys.alertButtonTitle.capsOk), ); } }; const authenticate = async () => { const isLoggedIn = await getLoginCredentials(email.trim(), password); // Checks // 1. USER_NOT_CONFIRMED_EXCEPTION // 2. BRAND_EXCEPTION_ERROR // 3. Generic error - which means we need to try again with email.toLowerCase() if ( !isLoggedIn.status && isLoggedIn.messageId === apiServerMessages.errors.USER_NOT_CONFIRMED_EXCEPTION ) { onNavigateToConfirmScreen(email.trim()); } else if (!isLoggedIn.status) { const isLoggedInWithLowerCaseEmail = await getLoginCredentials( email.trim().toLowerCase(), password, ); onLoginResponse(email.trim().toLowerCase(), isLoggedInWithLowerCaseEmail); } }; const onPressLoginBtn: ButtonOnPressType = async () => { Keyboard.dismiss(); showLoader(true); const isValidEmail = validateEmail(email.trim()); const isValidPassword = validatePassword(password); if (!isValidEmail) { showAlert( translate(translationKeys.alertDescription.invalidEmail), translate(translationKeys.alertTitle.invalidEmail), translate(translationKeys.alertButtonTitle.capsOk), ); } else if (!isValidPassword) { showAlert( translate(translationKeys.alertDescription.invalidPassword), translate(translationKeys.alertTitle.invalidPassword), translate(translationKeys.alertButtonTitle.tryAgain), ); } else { /** * Whenever user press login we are checking if network is connected then we are clearing out the stored credentials in keychain * Also resetting location state & auth state */ const {isConnected} = networkStatus; if (isConnected) { dispatch(resetLocationState()); dispatch(resetAuthState()); await KeyChain.resetInternetCredentials( keyChainICServers.DOH_APP_SERVER, ); setIsLoginCredentialsPresent(false); } await authenticate(); } }; /** Sub View */ const loginCard = () => { return ( <View style={styles.cardView}> <TextInput placeholder={translate(translationKeys.EmailPlaceholder)} keyBoardType="email-address" value={email} onChangeText={onChangeTextEmail} /> <TextInput containerStyle={styles.textInputContainer} placeholder={translate(translationKeys.PasswordPlaceholder)} isSecure value={password} onChangeText={onChangeTextPassword} /> <Button title={translate(translationKeys.LogIn)} onPress={onPressLoginBtn} /> <BiometricView isLoginCredentialsPresent={isLoginCredentialsPresent} onAuthenticated={() => { return onNavigate(); }} /> <Divider type="horizontal" /> <View style={styles.row}> <SecondaryButton title={translate(translationKeys.ButtonForgotPassword)} onPress={() => { navigation.navigate("ForgotPasswordScreen"); }} /> <Divider type="vertical" /> <SecondaryButton title={translate(translationKeys.ButtonCreateAccount)} onPress={() => { navigation.navigate("TermsAndConditionsScreen"); }} /> </View> </View> ); }; const renderRootScreen = () => { if (isLoginCredentialsPresent === null) { showLoader(true); } const {updateStatus} = settingsState; const {isUpdateAvailable} = updateStatus; if (isUpdateAvailable) { showLoader(false); return null; } return <RootScreen onCallback={onCallback} />; }; /** Main view */ return ( <Background keyBoardHandled keyboardVerticalOffset={useHeaderHeight()}> {renderRootScreen()} <Alert visible={alertStatus.isVisible} title={alertStatus.title} description={alertStatus.message} positiveButtonTitle={alertStatus.buttonTitle} onPress={alertStatus.onPress || onDismissAlert} /> <StatusBar translucent barStyle="dark-content" backgroundColor="transparent" /> <ImageBackground style={styles.backgroundImage} source={{uri: getBackgroundImage(themeId)}} > <SafeAreaView> <ScrollView style={styles.container} scrollEnabled={isKeyBoardOpen} showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled" > <View style={styles.cardContainer}> <Image style={styles.logo} resizeMode={DeviceInfo.isTablet() ? "contain" : "cover"} resizeMethod="scale" source={{uri: getLogo(themeId)}} /> <Card>{loginCard()}</Card> </View> </ScrollView> <BiometricAlert show={isAlertVisible} /> </SafeAreaView> </ImageBackground> </Background> );};
export default LoginScreen; explain this stepwise in detail and should be easy to understand
- Assistant
Certainly! Let's break down the
LoginScreencomponent step-by-step to understand its structure, functionality, and behavior. This comprehensive explanation will cover each part of the code, making it easier to grasp even if you're new to React Native or TypeScript.
Table of Contents
- Overview
- Imports
- Type Definitions
- Component Initialization
- State Variables
- Side Effects and Hooks
- Helper Functions
- Subcomponents
- Main Render Method
- Export
- Conclusion
Overview
The
LoginScreencomponent is a functional React Native component built using TypeScript. It serves as the login interface for an application, handling user input for email and password, managing authentication, displaying alerts, and handling navigation based on user actions and authentication status.
Imports
The component starts by importing various modules, libraries, and resources needed for its functionality:
React and React Native
import React, { FC, useCallback, useContext, useEffect, useState } from "react"; import { Image, ImageBackground, Keyboard, Platform, SafeAreaView, ScrollView, StatusBar, View, } from "react-native";- React & Hooks: Core React library and hooks like
useState,useEffect, etc. - React Native Components: UI components like
View,Image,ScrollView, etc.
Navigation
import { useHeaderHeight } from "@react-navigation/elements"; import { useFocusEffect } from "@react-navigation/native"; import { StackNavigationProp } from "@react-navigation/stack";- useFocusEffect: Executes effects when the screen is focused.
- StackNavigationProp: Type definition for navigation props.
Device Information and Security
import DeviceInfo from "react-native-device-info"; import KeyChain from "react-native-keychain";- DeviceInfo: Retrieves device-specific information.
- KeyChain: Handles secure storage of credentials.
Custom Components
import Alert from "@components/alert"; import Background from "@components/background"; import BiometricAlert from "@components/biometricAlert"; import Card from "@components/card"; import Divider from "@components/divider"; import TextInput from "@components/input"; import Button from "@components/primaryButton"; import SecondaryButton from "@components/secondaryButton";- Custom UI Components: Reusable components like
Alert,Button,Card, etc.
Configuration and Constants
import { apiServerMessages } from "@config/constants/APIMessagesConstants"; import { IS_DEVICE_REGISTERED_TO_PUSH_NOTIFICATION } from "@config/constants/AppConstants"; import { keyChainICServers } from "@config/constants/AuthConstants"; // ... (other imports)- Constants and Configurations: Various constants for API messages, app constants, authentication, error messages, etc.
Utilities and Services
import AppUtil from "@utils/AppUtil"; import { validateEmail, validatePassword } from "@utils/InputValidationUtil"; import { turnOffAllNotifications } from "@utils/PushNotificationsUtil"; // ... (other imports)- Utility Functions: Helper functions for validation, notifications, etc.
- Services: Async storage, Firebase services, etc.
Store and State Management
import { resetAuthState, updateAuthPersistState, updateManualLoginStatus } from "@store/auth/AuthSlice"; // ... (other imports) import { useAppDispatch, useAppSelector } from "@store/Hooks";- Redux Slices and Actions: Managing authentication, user details, location, loader state, etc.
- Hooks: Custom hooks for dispatching actions and selecting state.
Theming and Styles
import { getCurrentTheme, getSystemTheme, useThemeAwareObject, } from "@styles/theming/ThemingHelper"; import Styles from "./Styles";- Theming Helpers: Functions and hooks to manage theming and styles.
- Styles: Style definitions specific to the
LoginScreen.
Subcomponents and Utilities Specific to LoginScreen
import BiometricView from "./components/BiometricView"; import { getBackgroundImage, getLogo } from "./Utils";- BiometricView: Component handling biometric authentication UI.
- Utility Functions: Functions to get background images and logos based on themes.
Type Definitions
TypeScript types are defined to ensure type safety, especially for navigation props.
Navigation Prop Type
type LoginScreenNavigationProp = StackNavigationProp< AuthNavigatorParamList, "LoginScreen" >;- LoginScreenNavigationProp: Defines the navigation prop type specific to the
LoginScreen, usingAuthNavigatorParamListwhich should be defined elsewhere in the app.
Component Props
type Props = { navigation: LoginScreenNavigationProp; };- Props: The component receives a
navigationprop of typeLoginScreenNavigationProp.
Component Initialization
Functional Component Definition
const LoginScreen: FC<Props> = ({ navigation }: Props) => { // Component logic here... };- LoginScreen: A functional component that accepts
Props.
Initializers
Styles
const styles = useThemeAwareObject(Styles.createStyles);- styles: Uses a custom hook
useThemeAwareObjectto apply themed styles.
Localization
const { translate } = useContext(getLocalizationContext());- translate: Function to handle translations based on the current localization context.
Keyboard and Device Information
const isKeyBoardOpen = useKeyboard();- isKeyBoardOpen: Boolean indicating if the keyboard is open, using a custom
useKeyboardhook.
Redux Dispatch and Selector
const dispatch = useAppDispatch(); const settingsState = useAppSelector((state) => { return state.settingsReducer; });- dispatch: Function to dispatch Redux actions.
- settingsState: Selects the
settingsReducerstate from the Redux store.
Network and App State
const networkStatus = useIsNetworkReachable(); const appState = useAppState();- networkStatus: Information about network connectivity using a custom
useIsNetworkReachablehook. - appState: Current state of the app (e.g., active, background) using a custom
useAppStatehook.
Theme State
const [themeId, setThemeId] = useState<string>(getSystemTheme().themeId);- themeId: State variable to manage the current theme ID, initialized with the system theme.
State Variables
Several state variables are defined using the
useStatehook to manage component-specific data.const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isLoginCredentialsPresent, setIsLoginCredentialsPresent] = useState<boolean | null>(null); const [isAlertVisible, setIsAlertVisible] = useState(false); const [alertStatus, setAlertStatus] = useState<{ isVisible: boolean; title: string; message: string; onPress: Function | null; buttonTitle: string; }>({ isVisible: false, title: translate(defaultErrorTitle), message: "", onPress: null, buttonTitle: translate(translationKeys.alertButtonTitle.capsOk), });- email & password: Capture user input for email and password.
- isLoginCredentialsPresent: Indicates if login credentials are stored (e.g., for biometric login).
- isAlertVisible: Controls the visibility of alerts.
- alertStatus: Manages the content and behavior of alert messages, including title, message, button actions, etc.
Side Effects and Hooks
useFocusEffect
useFocusEffect( useCallback(() => { StatusBar.setBarStyle("dark-content"); if (Platform.OS === Platforms.android) { StatusBar.setTranslucent(true); StatusBar.setBackgroundColor("transparent"); } }, []), );- Purpose: Sets the status bar style and properties whenever the
LoginScreengains focus. - Behavior:
- Sets the status bar text to dark.
- On Android, makes the status bar translucent and transparent.
useEffect
useEffect(() => { (async () => { if (appState === AppState.active) { const theme = await getCurrentTheme(); setThemeId(theme.themeId); } })(); }, [styles.statusbar.backgroundColor, appState]);- Purpose: Updates the
themeIdstate whenever the app state changes or the status bar background color changes. - Behavior:
- If the app becomes active, fetches the current theme and updates
themeId.
- If the app becomes active, fetches the current theme and updates
Helper Functions
showLoader
const showLoader = (loading: boolean) => { if (navigation.isFocused()) { if (loading) { dispatch(showFanLoader()); } else { dispatch(hideFanLoader({ className: "LoginScreen" })); } } };- Purpose: Shows or hides a loader (spinner) based on the
loadingparameter. - Behavior:
- Checks if the current screen is focused.
- Dispatches Redux actions to show or hide the loader accordingly.
onNavigate
const onNavigate = async () => { // Dispatch actions to fetch user and location details dispatch(userThunkActions.getUserDetails()); dispatch(fetchDealerLocationInformation()); await dispatch(updateAuthPersistState()); };- Purpose: Fetches user details and dealer location information, and updates the authentication state.
- Behavior:
- Dispatches Redux thunks to perform asynchronous operations.
- Updates persisted authentication state.
Text Change Handlers
const onChangeTextEmail: TextInputOnChangeTextType = (id, text) => { setEmail(text); }; const onChangeTextPassword: TextInputOnChangeTextType = (id, text) => { setPassword(text); };- Purpose: Updates the
emailandpasswordstate variables when the user types in the respective input fields. - Parameters:
id: Identifier for the input field (not used here).text: The current text input by the user.
Alert Management
const onDismissAlert = () => { setAlertStatus({ isVisible: false, title: alertStatus.title, message: alertStatus.message, onPress: null, buttonTitle: alertStatus.buttonTitle, }); }; const showAlert = ( message: string, title: string, buttonTitle: string, onPress: Function | null = null, ) => { showLoader(false); setAlertStatus({ isVisible: appState === AppState.active, title, message, onPress, buttonTitle, }); };- onDismissAlert: Hides the alert by updating
alertStatus. - showAlert: Displays an alert with specified message, title, button title, and an optional press handler.
- Hides the loader.
- Sets
isVisiblebased on whether the app is active.
Navigation to Confirmation Screen
const onNavigateToConfirmScreen = async (email: string) => { showLoader(true); const resendResponse = await dispatch( userThunkActions.resendOtpForAccountCreation({ email }), ); if (resendResponse.meta.requestStatus === "fulfilled") { showLoader(false); navigation.navigate("ConfirmAccountScreen", { email, password, }); } else { const { message, httpStatusCode } = resendResponse.payload as iStateMessage; showLoader(false); if (httpStatusCode !== httpStatusCodes.NO_INTERNET) { showAlert( message as string, translate(defaultErrorTitle), translate(translationKeys.alertButtonTitle.capsOk), ); } } };- Purpose: Navigates the user to the "ConfirmAccountScreen" if their account isn't confirmed.
- Behavior:
- Shows the loader.
- Dispatches an action to resend OTP for account creation.
- If successful, navigates to the confirmation screen.
- If failed, shows an alert unless the failure is due to no internet.
Device Registration for Notifications
const registerDeviceForNotification = async ( email: string, ): Promise<boolean> => { try { const fcmToken = await getFCMToken(); if (fcmToken) { const appUUID = await AppUtil.getAppUUID(); await dispatch( userThunkActions.registerDeviceForNotification({ deviceInfo: { email, device_id: appUUID, device_token: fcmToken, device_type: Platform.OS, brand: AppUtil.getAppBrandName(), }, }), ).unwrap(); return true; } return false; } catch (error) { return false; } };- Purpose: Registers the device for push notifications using Firebase Cloud Messaging (FCM).
- Behavior:
- Retrieves the FCM token.
- If available, gathers device info and dispatches an action to register the device.
- Returns
trueif successful,falseotherwise.
Authentication Functions
getLoginCredentials
const getLoginCredentials = async ( email: string, password: string, ): Promise<{ status: boolean; httpStatusCode?: httpStatusCodes | null | undefined; messageId: string | null | undefined; title?: string | null | undefined; message: any; }> => { const loginDetails = await dispatch( authThunkActions.authenticate({ email, password }), ); if (loginDetails.meta.requestStatus === "fulfilled") { const userDetails = await dispatch(userThunkActions.getUserDetails()); if (userDetails.meta.requestStatus === "fulfilled") { const isRegistered = await registerDeviceForNotification(email.trim()); showLoader(false); setIsAlertVisible(true); if (isRegistered) { localStorage.setItem(IS_DEVICE_REGISTERED_TO_PUSH_NOTIFICATION, true); } else { turnOffAllNotifications(email.trim()); } dispatch(updateManualLoginStatus({ isManualLogin: true })); dispatch(fetchDealerLocationInformation()); return { status: true, messageId: null, message: "success", }; } const errorMessage = userDetails.payload as iStateMessage; return { status: false, httpStatusCode: errorMessage.httpStatusCode, messageId: errorMessage.messageId, title: errorMessage.title, message: errorMessage.message, }; } const errorMessage = loginDetails.payload as iStateMessage; return { status: false, httpStatusCode: errorMessage.httpStatusCode, messageId: errorMessage.messageId, title: errorMessage.title, message: errorMessage.message, }; };- Purpose: Handles the process of authenticating the user and fetching user details.
- Behavior:
- Dispatches an authentication action.
- If successful, fetches user details.
- Registers the device for notifications.
- Updates local storage and notification preferences based on registration success.
- Dispatches actions to update manual login status and fetch dealer location.
- Returns an object indicating the success or failure of the process.
onLoginResponse
const onLoginResponse = ( email: string, response: { status: boolean; httpStatusCode?: httpStatusCodes | null | undefined; messageId: string | null | undefined; title?: string | null | undefined; message: any; }, ) => { if ( !response.status && response.messageId === apiServerMessages.errors.USER_NOT_CONFIRMED_EXCEPTION ) { onNavigateToConfirmScreen(email); } else if (!response.status) { showAlert( translate(response.message || defaultErrorDescription), translate(defaultErrorTitle), translate(translationKeys.alertButtonTitle.capsOk), ); } };- Purpose: Handles the response from the authentication process.
- Behavior:
- If the user is not confirmed, navigates to the confirmation screen.
- If there's any other error, displays an alert with the error message.
authenticate
const authenticate = async () => { const isLoggedIn = await getLoginCredentials(email.trim(), password); if ( !isLoggedIn.status && isLoggedIn.messageId === apiServerMessages.errors.USER_NOT_CONFIRMED_EXCEPTION ) { onNavigateToConfirmScreen(email.trim()); } else if (!isLoggedIn.status) { const isLoggedInWithLowerCaseEmail = await getLoginCredentials( email.trim().toLowerCase(), password, ); onLoginResponse(email.trim().toLowerCase(), isLoggedInWithLowerCaseEmail); } };- Purpose: Initiates the authentication process.
- Behavior:
- Attempts to log in with the provided email and password.
- If the user's account isn't confirmed, navigates to the confirmation screen.
- If there's another error, retries with a lowercase email and handles the response.
onPressLoginBtn
const onPressLoginBtn: ButtonOnPressType = async () => { Keyboard.dismiss(); showLoader(true); const isValidEmail = validateEmail(email.trim()); const isValidPassword = validatePassword(password); if (!isValidEmail) { showAlert( translate(translationKeys.alertDescription.invalidEmail), translate(translationKeys.alertTitle.invalidEmail), translate(translationKeys.alertButtonTitle.capsOk), ); } else if (!isValidPassword) { showAlert( translate(translationKeys.alertDescription.invalidPassword), translate(translationKeys.alertTitle.invalidPassword), translate(translationKeys.alertButtonTitle.tryAgain), ); } else { const { isConnected } = networkStatus; if (isConnected) { dispatch(resetLocationState()); dispatch(resetAuthState()); await KeyChain.resetInternetCredentials(keyChainICServers.DOH_APP_SERVER); setIsLoginCredentialsPresent(false); } await authenticate(); } };- Purpose: Handles the login button press event.
- Behavior:
- Dismisses the keyboard.
- Shows the loader.
- Validates the email and password.
- If validation fails, shows appropriate alerts.
- If validation passes and the network is connected:
- Resets location and authentication state.
- Clears stored credentials.
- Sets
isLoginCredentialsPresenttofalse.
- Initiates the authentication process.
Subcomponents
loginCard
const loginCard = () => { return ( <View style={styles.cardView}> <TextInput placeholder={translate(translationKeys.EmailPlaceholder)} keyBoardType="email-address" value={email} onChangeText={onChangeTextEmail} /> <TextInput containerStyle={styles.textInputContainer} placeholder={translate(translationKeys.PasswordPlaceholder)} isSecure value={password} onChangeText={onChangeTextPassword} /> <Button title={translate(translationKeys.LogIn)} onPress={onPressLoginBtn} /> <BiometricView isLoginCredentialsPresent={isLoginCredentialsPresent} onAuthenticated={() => { return onNavigate(); }} /> <Divider type="horizontal" /> <View style={styles.row}> <SecondaryButton title={translate(translationKeys.ButtonForgotPassword)} onPress={() => { navigation.navigate("ForgotPasswordScreen"); }} /> <Divider type="vertical" /> <SecondaryButton title={translate(translationKeys.ButtonCreateAccount)} onPress={() => { navigation.navigate("TermsAndConditionsScreen"); }} /> </View> </View> ); };- Purpose: Renders the main login form.
- Components:
- TextInput for Email: Captures the user's email.
- TextInput for Password: Captures the user's password, secured (masked).
- Login Button: Triggers the login process.
- BiometricView: Handles biometric authentication if credentials are present.
- Divider: Visual separator.
- Secondary Buttons:
- Forgot Password: Navigates to the forgot password screen.
- Create Account: Navigates to the terms and conditions screen for account creation.
renderRootScreen
const renderRootScreen = () => { if (isLoginCredentialsPresent === null) { showLoader(true); } const { updateStatus } = settingsState; const { isUpdateAvailable } = updateStatus; if (isUpdateAvailable) { showLoader(false); return null; } return <RootScreen onCallback={onCallback} />; };- Purpose: Determines whether to display the
RootScreenor not. - Behavior:
- If
isLoginCredentialsPresentisnull, shows the loader. - Checks if an update is available:
- If yes, hides the loader and returns
null(no UI). - If no, renders the
RootScreencomponent with a callback.
- If yes, hides the loader and returns
- If
Main Render Method
return ( <Background keyBoardHandled keyboardVerticalOffset={useHeaderHeight()}> {renderRootScreen()} <Alert visible={alertStatus.isVisible} title={alertStatus.title} description={alertStatus.message} positiveButtonTitle={alertStatus.buttonTitle} onPress={alertStatus.onPress || onDismissAlert} /> <StatusBar translucent barStyle="dark-content" backgroundColor="transparent" /> <ImageBackground style={styles.backgroundImage} source={{ uri: getBackgroundImage(themeId) }} > <SafeAreaView> <ScrollView style={styles.container} scrollEnabled={isKeyBoardOpen} showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled" > <View style={styles.cardContainer}> <Image style={styles.logo} resizeMode={DeviceInfo.isTablet() ? "contain" : "cover"} resizeMethod="scale" source={{ uri: getLogo(themeId) }} /> <Card>{loginCard()}</Card> </View> </ScrollView> <BiometricAlert show={isAlertVisible} /> </SafeAreaView> </ImageBackground> </Background> );-
Overall Structure:
- Background: A custom component likely providing a background layout, handling keyboard behavior, and adjusting for the header height.
- renderRootScreen: Conditionally renders the
RootScreenbased on login credentials and update status. - Alert: Displays alert messages based on
alertStatus. - StatusBar: Configures the appearance of the device's status bar.
- ImageBackground: Sets a background image that changes based on the current theme.
- SafeAreaView: Ensures content isn't hidden behind device notches or other UI elements.
- ScrollView: Allows the content to be scrollable, especially when the keyboard is open.
- Content:
- Logo Image: Displays the app's logo, responsive to device type (tablet or not).
- Card: Encapsulates the
loginCardcomponent, providing a styled container.
-
Additional Components:
- BiometricAlert: Displays biometric authentication alerts when
isAlertVisibleistrue.
- BiometricAlert: Displays biometric authentication alerts when
Export
export default LoginScreen;- Purpose: Exports the
LoginScreencomponent as the default export, allowing it to be imported and used in other parts of the application.
Conclusion
The
LoginScreencomponent is a well-structured and comprehensive login interface for a React Native application. Here's a summary of its key functionalities:- User Input: Captures user email and password through controlled input fields.
- Validation: Validates user input for correct email format and password strength.
- Authentication: Handles user authentication by communicating with backend services using Redux thunks.
- Biometric Authentication: Supports biometric login methods if user credentials are stored.
- Push Notifications: Registers the device for push notifications upon successful login.
- Alerts: Displays informative alerts for various scenarios like validation errors, authentication failures, etc.
- Navigation: Navigates to different screens based on user actions and authentication status, such as account confirmation or password recovery.
- Theming and Styling: Adapts its appearance based on the current theme and device type.
- State Management: Utilizes Redux for managing global state related to authentication, user details, settings, and loading states.
- Responsive Design: Ensures the UI is responsive, handling keyboard visibility and different device types gracefully.
By leveraging React hooks, TypeScript types, and Redux for state management, the
LoginScreenprovides a robust and maintainable solution for user authentication within the application.