Creating an Auth Loading Screen in React Native

In this guide, we’ll walk through setting up an authentication loading screen in a React Native app using TypeScript. The purpose of the auth loading screen is to check the user’s authentication status and navigate them to the appropriate screen: admin, user, or the authentication screen.

Step 1: Creating the authloading.tsx File

Start by creating a file named authloading.tsx inside the src/app directory. This will be responsible for determining the user’s status and navigating them accordingly.

Code for authloading.tsx:
import React, { useEffect } from 'react';
import { View, ActivityIndicator } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation, NavigationProp } from '@react-navigation/native';
import { RootStack } from '@/src/types'; 

const AuthLoading = () => {
  const navigation = useNavigation<NavigationProp<RootStack>>();

  const checkUserStatus = async () => {
    try {
      // Retrieve the stored user data from AsyncStorage
      const userData = await AsyncStorage.getItem('user');
      
      if (userData) {
        const user = JSON.parse(userData);

        // Navigate based on the user’s screen property
        if (user.screen === 'admin') {
          navigation.navigate('(admin)');
        } else if (user.screen === 'user') {
          navigation.navigate('(user)'); 
        } else {
          navigation.navigate('(auth)');
        }
      } else {
        navigation.navigate('(auth)');
      }
    } catch (error) {
      console.error("Error fetching user data:", error);
      navigation.navigate('(auth)');  
    }
  };

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

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white' }}>
      <ActivityIndicator size="large" color="#0000ff" />
    </View>
  );
};

export default AuthLoading;
Explanation:
  • AsyncStorage is used to fetch the saved user data.
  • Based on the user’s screen value, the app navigates them to the appropriate screen: admin, user, or auth.
  • ActivityIndicator shows a loading spinner while checking the user’s status.
Step 2: Defining the Type for RootStack

Now, create a file named types.tsx in the src folder to define the navigation stack types.

Code for types.tsx:
export type RootStack = {
  '(admin)': undefined; 
  '(auth)': undefined;
  '(user)': undefined;   
  authloading: undefined;   
};

This type will ensure the navigation system knows the structure of your stack.

Step 3: Updating the _layout.tsx File

Next, modify the src/app/_layout.tsx file to set authloading.tsx as the initial route. This file controls the layout and flow of the app.

Updated src/app/_layout.tsx:
import FontAwesome from '@expo/vector-icons/FontAwesome';
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { useEffect } from 'react';
import 'react-native-reanimated';
import * as React from 'react'; 
import { useColorScheme } from '@/src/components/useColorScheme'; 

export const unstable_settings = { 
  initialRouteName: 'authloading',
};

// Prevent splash screen from auto-hiding
SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  const [loaded, error] = useFonts({
    SpaceMono: require('../../assets/fonts/SpaceMono-Regular.ttf'),
    ...FontAwesome.font,
  }); 

  useEffect(() => {
    if (error) throw error;
  }, [error]);

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
    }
  }, [loaded]);

  if (!loaded) {
    return null;
  }

  return <RootLayoutNav />;
}

function RootLayoutNav() {
  const colorScheme = useColorScheme();

  return (
    <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
      <Stack initialRouteName="authloading">
        <Stack.Screen name="(auth)" options={{ headerShown: false }} />
        <Stack.Screen name="(admin)" options={{ headerShown: false }} />
        <Stack.Screen name="(user)" options={{ headerShown: false }} />
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        <Stack.Screen name="modal" options={{ presentation: 'modal' }} />
      </Stack>
    </ThemeProvider>
  );
}
Key Changes:
  • The initial route is set to authloading to trigger the authentication check as soon as the app loads.
  • Other routes like (auth), (admin), and (user) are defined to handle navigation after authentication is determined.
Step 4: Setting Up Screen Folders

Ensure that the src/app directory contains the necessary folder structure. If you have set up react-navigation correctly, the (tabs) folder should already exist.

Create three additional folders:

  • (auth) for login and registration code
  • (user) for the user’s dashboard and related components
  • (admin) for the admin panel

Each folder will hold the respective screens and logic for authentication, user panels, and admin controls.

With these steps, you’ve now set up an authentication loading screen that checks the user’s status and navigates them to the appropriate screen. This ensures a smooth experience by directing users based on their roles right from the start!

Tripti

Leave a Reply

Your email address will not be published. Required fields are marked *