{"id":91,"date":"2024-10-13T16:31:15","date_gmt":"2024-10-13T16:31:15","guid":{"rendered":"https:\/\/blog.vyomscode.com\/?p=91"},"modified":"2024-10-13T16:31:15","modified_gmt":"2024-10-13T16:31:15","slug":"creating-an-auth-loading-screen-in-react-native","status":"publish","type":"post","link":"https:\/\/blog.vyomscode.com\/index.php\/2024\/10\/13\/creating-an-auth-loading-screen-in-react-native\/","title":{"rendered":"Creating an Auth Loading Screen in React Native"},"content":{"rendered":"\n<p>In this guide, we\u2019ll walk through setting up an authentication loading screen in a React Native app using TypeScript. The purpose of the <strong>auth loading screen<\/strong> is to check the user\u2019s authentication status and navigate them to the appropriate screen: admin, user, or the authentication screen.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Step 1: Creating the <\/strong><code><strong>authloading.tsx<\/strong><\/code><strong> File<\/strong><\/h5>\n\n\n\n<p>Start by creating a file named <strong><code>authloading.tsx<\/code><\/strong> inside the <code>src\/app<\/code> directory. This will be responsible for determining the user\u2019s status and navigating them accordingly.<\/p>\n\n\n\n<h6 class=\"wp-block-heading\"><strong>Code for <code>authloading.tsx<\/code>:<\/strong><\/h6>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useEffect } from 'react';\r\nimport { View, ActivityIndicator } from 'react-native';\r\nimport AsyncStorage from '@react-native-async-storage\/async-storage';\r\nimport { useNavigation, NavigationProp } from '@react-navigation\/native';\r\nimport { RootStack } from '@\/src\/types'; \r\n\r\nconst AuthLoading = () => {\r\n  const navigation = useNavigation&lt;NavigationProp&lt;RootStack>>();\r\n\r\n  const checkUserStatus = async () => {\r\n    try {\r\n      \/\/ Retrieve the stored user data from AsyncStorage\r\n      const userData = await AsyncStorage.getItem('user');\r\n      \r\n      if (userData) {\r\n        const user = JSON.parse(userData);\r\n\r\n        \/\/ Navigate based on the user\u2019s screen property\r\n        if (user.screen === 'admin') {\r\n          navigation.navigate('(admin)');\r\n        } else if (user.screen === 'user') {\r\n          navigation.navigate('(user)'); \r\n        } else {\r\n          navigation.navigate('(auth)');\r\n        }\r\n      } else {\r\n        navigation.navigate('(auth)');\r\n      }\r\n    } catch (error) {\r\n      console.error(\"Error fetching user data:\", error);\r\n      navigation.navigate('(auth)');  \r\n    }\r\n  };\r\n\r\n  useEffect(() => {\r\n    checkUserStatus();\r\n  }, &#91;]);\r\n\r\n  return (\r\n    &lt;View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white' }}>\r\n      &lt;ActivityIndicator size=\"large\" color=\"#0000ff\" \/>\r\n    &lt;\/View>\r\n  );\r\n};\r\n\r\nexport default AuthLoading;\r\n<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Explanation:<\/strong><\/h5>\n\n\n\n<ul>\n<li><strong>AsyncStorage<\/strong> is used to fetch the saved user data.<\/li>\n\n\n\n<li>Based on the user\u2019s <code>screen<\/code> value, the app navigates them to the appropriate screen: admin, user, or auth.<\/li>\n\n\n\n<li><strong>ActivityIndicator<\/strong> shows a loading spinner while checking the user\u2019s status.<\/li>\n<\/ul>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Step 2: Defining the Type for <code>RootStack<\/code><\/strong><\/h5>\n\n\n\n<p>Now, create a file named <strong><code>types.tsx<\/code><\/strong> in the <code>src<\/code> folder to define the navigation stack types.<\/p>\n\n\n\n<h6 class=\"wp-block-heading\"><strong>Code for <code>types.tsx<\/code>:<\/strong><\/h6>\n\n\n\n<pre class=\"wp-block-code\"><code>export type RootStack = {\r\n  '(admin)': undefined; \r\n  '(auth)': undefined;\r\n  '(user)': undefined;   \r\n  authloading: undefined;   \r\n};\r\n<\/code><\/pre>\n\n\n\n<p>This type will ensure the navigation system knows the structure of your stack.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Step 3: Updating the <code>_layout.tsx<\/code> File<\/strong><\/h5>\n\n\n\n<p>Next, modify the <code>src\/app\/_layout.tsx<\/code> file to set <code>authloading.tsx<\/code> as the initial route. This file controls the layout and flow of the app.<\/p>\n\n\n\n<h6 class=\"wp-block-heading\"><strong>Updated <code>src\/app\/_layout.tsx<\/code>:<\/strong><\/h6>\n\n\n\n<pre class=\"wp-block-code\"><code>import FontAwesome from '@expo\/vector-icons\/FontAwesome';\r\nimport { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation\/native';\r\nimport { useFonts } from 'expo-font';\r\nimport { Stack } from 'expo-router';\r\nimport * as SplashScreen from 'expo-splash-screen';\r\nimport { useEffect } from 'react';\r\nimport 'react-native-reanimated';\r\nimport * as React from 'react'; \r\nimport { useColorScheme } from '@\/src\/components\/useColorScheme'; \r\n\r\nexport const unstable_settings = { \r\n  initialRouteName: 'authloading',\r\n};\r\n\r\n\/\/ Prevent splash screen from auto-hiding\r\nSplashScreen.preventAutoHideAsync();\r\n\r\nexport default function RootLayout() {\r\n  const &#91;loaded, error] = useFonts({\r\n    SpaceMono: require('..\/..\/assets\/fonts\/SpaceMono-Regular.ttf'),\r\n    ...FontAwesome.font,\r\n  }); \r\n\r\n  useEffect(() => {\r\n    if (error) throw error;\r\n  }, &#91;error]);\r\n\r\n  useEffect(() => {\r\n    if (loaded) {\r\n      SplashScreen.hideAsync();\r\n    }\r\n  }, &#91;loaded]);\r\n\r\n  if (!loaded) {\r\n    return null;\r\n  }\r\n\r\n  return &lt;RootLayoutNav \/>;\r\n}\r\n\r\nfunction RootLayoutNav() {\r\n  const colorScheme = useColorScheme();\r\n\r\n  return (\r\n    &lt;ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>\r\n      &lt;Stack initialRouteName=\"authloading\">\r\n        &lt;Stack.Screen name=\"(auth)\" options={{ headerShown: false }} \/>\r\n        &lt;Stack.Screen name=\"(admin)\" options={{ headerShown: false }} \/>\r\n        &lt;Stack.Screen name=\"(user)\" options={{ headerShown: false }} \/>\r\n        &lt;Stack.Screen name=\"(tabs)\" options={{ headerShown: false }} \/>\r\n        &lt;Stack.Screen name=\"modal\" options={{ presentation: 'modal' }} \/>\r\n      &lt;\/Stack>\r\n    &lt;\/ThemeProvider>\r\n  );\r\n}\r\n<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Key Changes:<\/strong><\/h5>\n\n\n\n<ul>\n<li>The initial route is set to <strong><code>authloading<\/code><\/strong> to trigger the authentication check as soon as the app loads.<\/li>\n\n\n\n<li>Other routes like <code>(auth)<\/code>, <code>(admin)<\/code>, and <code>(user)<\/code> are defined to handle navigation after authentication is determined.<\/li>\n<\/ul>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Step 4: Setting Up Screen Folders<\/strong><\/h5>\n\n\n\n<p>Ensure that the <code>src\/app<\/code> directory contains the necessary folder structure. If you have set up <strong>react-navigation<\/strong> correctly, the <code>(tabs)<\/code> folder should already exist.<\/p>\n\n\n\n<p>Create three additional folders:<\/p>\n\n\n\n<ul>\n<li><strong>(auth)<\/strong> for login and registration code<\/li>\n\n\n\n<li><strong>(user)<\/strong> for the user\u2019s dashboard and related components<\/li>\n\n\n\n<li><strong>(admin)<\/strong> for the admin panel<\/li>\n<\/ul>\n\n\n\n<p>Each folder will hold the respective screens and logic for authentication, user panels, and admin controls.<\/p>\n\n\n\n<p>With these steps, you\u2019ve now set up an authentication loading screen that checks the user\u2019s status and navigates them to the appropriate screen. This ensures a smooth experience by directing users based on their roles right from the start!<\/p>\n\n\n\n<p>&#8211; <a href=\"https:\/\/tripti.vyomscode.com\/\" data-type=\"link\" data-id=\"https:\/\/tripti.vyomscode.com\/\">Tripti<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, we\u2019ll walk through setting up an authentication loading screen in a React Native app using TypeScript. The purpose of the auth loading screen is to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"_links":{"self":[{"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/posts\/91"}],"collection":[{"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/comments?post=91"}],"version-history":[{"count":1,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/posts\/91\/revisions"}],"predecessor-version":[{"id":92,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/posts\/91\/revisions\/92"}],"wp:attachment":[{"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/media?parent=91"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/categories?post=91"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/tags?post=91"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}