Stacknavigator React Native Goes to Screen Then Back Again

  • 22 min read
  • JavaScript, React, Tools

Quick summary ↬ Often you need two dissimilar sets of navigation stacks for pre and post user hallmark. Usually, to see more content, you have to be authenticated in some mode. Let'southward look at how to mount and unmount navigation stack based on a met condition in React Native.

In this article, we are going to walk through mounting and unmounting of navigation routes in React Native. An expected beliefs of your app is that once the hallmark condition is met, a new set of navigation routes are available just to logged-in users, while the other screens which were displayed before hallmark is removed and can't be returned to unless the user signs out of the awarding.

For security in your app, protected routes provide you with a way to simply display certain information/content on your app to specific users, while restricting access from unauthorized persons.

We volition exist working with Expo for this project because it'll assistance united states focus on the problem at mitt instead of worrying about a lot of setups. The exact same steps in this article could exist followed for a bare React Native application.

You need some familiarity with JavaScript and React Native to follow through with this tutorial. Here are a few of import things you should already be familiar with:

  • Custom components in React Native (how to create components, receive, laissez passer, and use props in a component). Read more than.
  • React Navigation. Read more.
  • Stack Navigator in React Native. Read more.
  • Bones Knowledge of React Native Core components (<View/>, <Text/>, etc.). Read more than.
  • React Native AsyncStorage. Read more.
  • Context API. Read more.

Project Setup And Base Authentication

If you lot're new to using expo and don't know how to install expo, visit the official documentation. Once the installation is consummate, become ahead to initialize a new React Native projection with expo from our command prompt:

          expo init navigation-projection        

You will be presented with some options to choose how yous want the base of operations setup to be:

React Native project's base setup
(Large preview)

In our case, allow's select the start pick to set up our project as a bare document. Now, wait until the installation of the JavaScript dependencies is complete.

Once our app is set up, we can change our directory to our new project directory and open it in your favorite code editor. Nosotros demand to install the library nosotros will exist using for AsyncStorage and our navigation libraries. Inside your folder directory in your terminal, paste the command above and choose a template (bare would work) to install our project dependencies.

Let's expect at what each of these dependencies is for:

  • @react-native-customs/async-storage
    Like localStorage on the spider web, information technology is a React Native API for persisting data on a device in key-value pairs.
  • @react-native-community/masked-view, react-native-screens, react-native-gesture-handle
    These dependencies are cadre utilities that are used by most navigators to create the navigation structure in the app. (Read more in Getting started with React Native navigation.)
  • @react-navigation/native
    This is the dependency for React Native navigation.
  • @react-navigation/stack
    This is the dependency for stack navigation in React Native.
            npm install @react-native-community/async-storage @react-native-community/masked-view @react-navigation/native @react-navigation/stack react-native-screens react-native-gesture-handle          

To kickoff the application utilise expo start from the app directory in your final. Once the app is started, yous tin can apply the expo app from your mobile phone to scan the bar code and view the application, or if you lot have an android emulator/IOS simulator, you can open the app through them from the expo developer tool that opens upwardly in your browser when you start an expo application. For the images examples in this commodity, nosotros will be using Genymotions to see our result. Here'south what our terminal result will look similar in Genymotions:

final result in Genymotions
(Large preview)

Folder Structures

Let us create our folder structure from the outset so that it'south easier for u.s. to work with it as we go along:

We need two folders kickoff:

  • context
    This folder will hold the context for our entire application as we will be working with Context API for global land management.
  • views
    This folder will hold both the navigation folder and the views for dissimilar screens.

Go ahead and create the two folders in your project directory.

Within the context folder, create a folder chosen authContext and create two file inside of the authContext folder:

  • AuthContext.js,
  • AuthState.js.

We will need these files when we start working with Context API.

Now go to the views folder we created and create two more folders inside of it, namely:

  • navigation,
  • screens.

Now, nosotros are not yet finished, within the screens binder, create these ii more folders:

  • postAuthScreens,
  • preAuthScreens.

If you lot followed the folder setup correctly, this is how your folder construction should await similar at the moment:

folder structure
(Large preview)

More after jump! Continue reading below ↓

Creating Our Kickoff Screen

Now let'due south create our first screen and call it the welcomeScreen.js inside the preAuthScreens folder.

preAuthScreens > welcomeScreen.js

Here'southward the content of our welcomeScreen.js file:

            import React from 'react'; import { View, Text, Button, StyleSheet, TextInput } from 'react-native';  const WelcomeScreen = () => {    const onUserAuthentication = () => {     console.log("User authentication button clicked")   }    return (     <View fashion={styles.container}>       <Text mode={styles.header}>Welcome to our App!</Text>       <View>         <TextInput style={styles.inputs} placeholder="Enter your email hither.." />         <TextInput style={styles.inputs} secureTextEntry={true} placeholder="Enter your password here.." /> <Button  title="AUTHENTICATE" onPress={onUserAuthentication} />       </View>     </View>   ) }  const styles = StyleSheet.create({   container: {     flex: i,     backgroundColor: '#fff',     alignItems: 'center',     justifyContent: 'center',   },   header: {     fontSize: 25,     fontWeight: 'bold',     marginBottom: 30   },   inputs: {     width: 300,     height: 40,     marginBottom: 10,     borderWidth: one,   } })  export default WelcomeScreen                      

Here's what nosotros did in the code block in a higher place:

Commencement, nosotros imported the things we need from the React Native library, namely, View, Text, Push, TextInput. Next, nosotros created our functional component WelcomeScreen.

You'll notice that we imported the StyleSheet from React Native and used it to ascertain styles for our header and too our <TextInput />.

Lastly, nosotros export the WelcomeScreen component at the bottom of the code.

Now that we are done with this, let's become this component to function as expected by using the useState hook to store the values of the inputs and update their states anytime a change happens in the input fields. We will also bring import the useCallback hook from React as we will be needing it afterward to hold a role.

First, while we are however in the WelcomeScreen component, we need to import the useState and useCallback from React.

          import React, { useState, useCallback } from 'react';        

Now within the WelcomeScreen functional component, let's create the 2 states for the email and password respectively:

          ... const WelcomeScreen = () => {   const [email, setEmail] = useState('')   const [password, setPassword] = useState('')   return (     ...   ) } ...        

Next, we need to modify our <TextInput /> fields so that the become their value from their respective states and update their state when the value of the input is updated:

            import React, { useState, useCallback } from 'react'; import { View, Text, Push button, StyleSheet, TextInput } from 'react-native';  const WelcomeScreen = () => {   const [e-mail, setEmail] = useState('')   const [password, setPassword] = useState('')    const onInputChange = (value, setState) => {     setState(value);   }   render (     <View>       ...             <View>         <TextInput           fashion={styles.inputs}           placeholder="Enter your e-mail hither.."           value={email}           onChangeText={(value) => onInputChange(value, setEmail)}         />         <TextInput           style={styles.inputs}           secureTextEntry={truthful}           placeholder="Enter your password hither.."           value={password}           onChangeText={(value) => onInputChange(value, setPassword)}         />         ...       </View>     </View>   ) } ...                      

In the code above, here is what we did:

  • We made the value of each of the text inputs to point to their respective states.
  • We added the onChangeText handler to our text inputs. This fires upward anytime a new value is entered or deleted from the input fields.
  • We called our onInputChange function which accepts two arguments:
    • The current value is supplied by the onChangeText handler.
    • The setter of the land that should be updated (for the first input field nosotros laissez passer setEmail and the 2d we pass setPassword.
    • Finally, we write our onInputChange role, and our office does only one affair: Information technology updates the respective states with the new value.

The next matter we need to piece of work on is the onUserAuthentication() function with is chosen whenever the button for the form submission is clicked.

Ideally, the user must have already created an business relationship and login volition involve some backend logic of some sort to bank check that the user exists and then assign a token to the user. In our case, since we are not using any backend, we volition create an object property the correct user login detail, and so only cosign a user when the values they enter matches our fixed values from the login object of email and password that we will create.

Here's the code we need to practice this:

            ...  const correctAuthenticationDetails = {   email: 'demouser@gmail.com',   password: 'password' } const WelcomeScreen = () => {   ...    // This role gets called when the `Authenticate` button is clicked   const onUserAuthentication = () => {     if (       email !== correctAuthenticationDetails.e-mail ||       password !== correctAuthenticationDetails.password     ) {       alert('The e-mail or password is incorrect')       return     }       // In here, we will handle what happens if the login details are       // correct   }    ...   return (     ...   ) } ...                      

One of the start things you'll notice in the code above is that nosotros divers a correctAuthenticationDetails (which is an object that holds the correct login details we look a user to supply) outside of the WelcomeScreen() functional component.

Next, nosotros wrote the content of the onUserAuthentication() function and used a provisional statement to check if the e-mail or password held in the respective states does non match the i we supplied in our object.

If you would like to see what we have done and so far, import the WelcomeScreen component into your App.js like this:

Open the App.js file and put this replace the entire code with this:

            import { StatusBar } from 'expo-status-bar'; import React from 'react'; import { View } from 'react-native'; import WelcomeScreen from './views/screens/preAuthScreens/welcomeScreen'; export default function App() {   return (     <View>       <StatusBar style="car" />       <WelcomeScreen />     </View>   ); }                      

Looking closely at the code in a higher place, you'll see that what we did was import the WelcomeScreen component and so used it in the App() function.

Here'due south what the result looks like of our WelcomeScreen looks like:

the result of WelcomeScreen
(Large preview)

Now that we are done building the WelcomeScreen component, let's move ahead and showtime working with Context API for managing our global state.

Why Context API?

Using Context API, we do not need to install any additional library into ReactJS, it is less stressful to set upwards, and is i of the most popular ways of handling global land in ReactJS. For lightweight state management, it is a expert choice.

Creating Our Context

If you lot recall, we created a context folder earlier and created a subfolder inside of it called the authContext.

Now let'south navigate to the AuthContext.js file in the authContext folder and create our context:

context > authContext > AuthContext.js

                      import React, { createContext } from 'react'; const AuthContext = createContext(); export default AuthContext;                  

The AuthContext we only created holds the loading state value and the userToken country values. Currently, in the createContext nosotros alleged in the code-block in a higher place, we didn't initialize any default values here then our context is currently undefined. An example value of the auth context could be {loading: false, userToken: 'abcd}

The AuthState.js file holds our Context API logic and their state values. Functions written here can be chosen from anywhere in our app and when they update values in land, it is updated globally likewise.

First, allow'south bring in all the imports we volition demand in this file:

context > AuthContext > AuthState.js

            import React, { useState } from 'react'; import AuthContext from './AuthContext'; import AsyncStorage from '@react-native-customs/async-storage';          

We imported the useState() hook from ReactJS to hold our states, we imported the AuthContext file we created above because this is where our empty context for authentication is initialized and we will need to use it as you'll see later on while we progress, finally we import the AsyncStorage package (similar to localStorage for the web).

AsyncStorage is a React Native API that allows you to persist information offline over the device in a React Native application.

          ...  const AuthState = (props) => {     const [userToken, setUserToken] = useState(null);     const [isLoading, setIsLoading] = useState(true);      const onAuthentication = async() => {         const USER_TOKEN = "drix1123q2"         await AsyncStorage.setItem('user-token', USER_TOKEN);         setUserToken(USER_TOKEN);         panel.warn("user has been authenticated!")     }      render (         <AuthContext.Provider             value={{                 onAuthentication,             }}         >             {props.children}         </AuthContext.Provider>     ) } export default AuthState;                  

In the lawmaking cake above here'south what we did:

  • We declared 2 states for the userToken and isLoading. The userToken state volition exist used to store the token saved to AsyncStorage, while the isLoading state volition exist used to track the loading status (initially information technology is set up to true). We will discover out more about the use of these two states equally nosotros go on.

  • Side by side, we wrote our onAuthentication() function. This function is an async function that gets called when the login button is clicked from the welcomeScreen.jsx file. This function will simply go chosen if the electronic mail and countersign the user has supplied matches the correct user detail object we provided. Usually what happens during hallmark is that a token is generated for the user after the user is authenticated on the backend using a package similar JWT, and this token is sent to the frontend. Since we are not going into all of that for this tutorial, we created a static token and kept information technology in a variable called USER_TOKEN.

  • Side by side, nosotros use the expect keyword to set our user token to AsyncStorage with the proper name user-token. The console.warn() statement is merely used to check that everything went right, you can take information technology off whenever y'all similar.

  • Finally, we laissez passer our onAuthenticated function every bit a value inside our <AuthContext.Provider> so that nosotros can access and call the part from anywhere in our app.

screens > preAuth > welcomeScreen.js

Showtime, import useContext from ReactJS and import the AuthContext from the AuthContext.js file.

            import React, { useState, useContext } from 'react'; import AuthContext from '../../../context/authContext/AuthContext' ...          

Now, inside the welcomeScreen() functional component, allow's use the context which nosotros have created:

          ... const WelcomeScreen = () => {   const { onAuthentication } = useContext(AuthContext)   const onUserAuthentication = () => {     if (       email !== correctAuthenticationDetails.email ||       password !== correctAuthenticationDetails.password     ) {       alert('The email or password is incorrect')       return     }     onAuthentication()   }   return (     ...   ) } ...                  

In the above code block, we destructured the onAuthentication function from our AuthContext and so we called information technology inside our onUserAuthentication() function and removed the console.log() argument which was there earlier now.

Correct now, this will throw an error considering we don't notwithstanding have access to the AuthContext. To use the AuthContext anywhere in your application, we need to wrap the top-level file in our app with the AuthState (in our case, it is the App.js file).

Go to the App.js file and supersede the lawmaking in that location with this:

            import React from 'react'; import WelcomeScreen from './views/screens/preAuthScreens/welcomeScreen'; import AuthState from './context/authContext/AuthState'  export default office App() {   return (     <AuthState>       <WelcomeScreen />     </AuthState>   ); }                      

Nosotros've come up so far and nosotros're done with this section. Earlier we move into the side by side section where we prepare our routing, let's create a new screen. The screen nosotros are about to create will be the HomeScreen.js file which is supposed to show up simply afterward successful authentication.

Go to: screens > postAuth.

Create a new file called HomeScreen.js. Here's the code for the HomeScreen.js file:

screens > postAuth > HomeScreen.js

          import React from 'react'; import { View, Text, Push button, StyleSheet } from 'react-native';  const HomeScreen = () => {    const onLogout = () => {     console.warn("Logout button cliked")   }    render (     <View style={styles.container}>       <Text>Now you're authenticated! Welcome!</Text>       <Push button title="LOG OUT" onPress={onLogout} />     </View>   ) }  const styles = StyleSheet.create({   container: {     flex: 1,     backgroundColor: '#fff',     alignItems: 'middle',     justifyContent: 'middle',   }, })  consign default HomeScreen                  

For at present, the logout button has a dummy console.log() statement. Subsequently, we will create the logout functionality and pass it to the screen from our context.

Setting Up Our Routes

We need to create three (three) files inside our navigation folder:

  • postAuthNavigator.js,
  • preAuthNavigator.js,
  • AppNavigator.js.

One time you've created these three files, navigate to the preAuthNaviagtor.js file you just created and write this:

navigation > preAuthNavigator.js

            import React from "react"; import { createStackNavigator } from "@react-navigation/stack"; import WelcomeScreen from "../screens/preAuthScreens/welcomeScreen";  const PreAuthNavigator = () => {     const { Navigator, Screen } = createStackNavigator();      return (         <Navigator initialRouteName="Welcome">             <Screen                 proper noun="Welcome"                 component={WelcomeScreen}             />         </Navigator>     ) } export default PreAuthNavigator;                      

In the file in a higher place, here'south what we did:

  • We imported the createStackNavigator from the @react-navigation/stack which nosotros are using for our stack navigation. The createStackNavigatorProvides a way for your app to transition between screens where each new screen is placed on top of a stack. Past default the stack navigator is configured to have the familiar iOS and Android look & feel: new screens slide in from the right on iOS, fade in from the bottom on Android. Click here if you want to learn more about the stack navigator in React Native.
  • We destructured Navigator and Screen from the createStackNavigator().
  • In our render argument, we created our navigation with the <Navigator/> and created our screen with the <Screen/>. this means that if nosotros had multiple screens that can be accessed before authentication, we volition take multiple <Screen/> tags here representing them.
  • Finally, we export our PreAuthNavigator component.

Let us practise a similar affair for the postAuthNavigator.js file.

navigation > postAuthNavigator.js

            import React from "react"; import { createStackNavigator } from "@react-navigation/stack"; import HomeScreen from "../screens/postAuthScreens/HomeScreen"; const PostAuthNavigator = () => {   const { Navigator, Screen} = createStackNavigator();   return (     <Navigator initialRouteName="Home">       <Screen         proper noun="Home"         component={HomeScreen}       />     </Navigator>    ) } consign default PostAuthNavigator;                      

As we see in the code above, the only deviation betwixt the preAuthNavigator.js and the postAuthNavigator.js is the screen being rendered. While the first one takes the WelcomeScreen, the postAuthNavigator.js takes the HomeScreen.

To create our AppNavigator.js nosotros demand to create a few things.

Since the AppNavigator.js is where nosotros volition exist switching and checking which route will be available for access by the user, we need several screens in place for this to work properly, let'southward outline the things we demand to create first:

  1. TransitionScreen.js
    While the app decides which navigation it is going to mount, we want a transition screen to evidence up. Typically, the transition screen will be a loading spinner or any other custom animation chosen for the app, but in our example, nosotros will utilise a basic <Text/> tag to display loading… .
  2. checkAuthenticationStatus()
    This office is what we will exist calling to check the authentication condition which will make up one's mind which navigation stack is going to exist mounted. We will create this function in our context and use it in the Appnavigator.js.

Now, allow's go ahead and create our TransitionScreen.js file.

screens > TransitionScreen.js

          import React from 'react'; import { Text, View } from 'react-native';  const TransitionScreen = () => {   return (     <View>       <Text>Loading...</Text>     </View>   ) }  export default TransitionScreen                  

Our transition screen is simply a uncomplicated screen that shows loading text. Nosotros volition see where to employ this as we continue in this commodity.

Adjacent, let us go to our AuthState.js and write our checkAuthenticationStatus():

context > authContext > AuthState.js

            import React, { useState, useEffect } from 'react'; import AuthContext from './AuthContext'; import AsyncStorage from '@react-native-community/async-storage';  const AuthState = (props) => {     const [userToken, setUserToken] = useState(nil);     const [isLoading, setIsLoading] = useState(true);      ...     useEffect(() => {         checkAuthenticationStatus()     }, [])          const checkAuthenticationStatus = async () => {         try {             const returnedToken = await AsyncStorage.getItem('user-toke             n');             setUserToken(returnedToken);             console.warn('User token gear up to the state value)         } catch(err){             console.warn(`Here's the error that occured while retrievin             yard token: ${err}`)          }         setIsLoading(false)     }       const onAuthentication = async() => {         ...     }      return (         <AuthContext.Provider             value={{                 onAuthentication,                 userToken,                 isLoading,             }}         >             {props.children}         </AuthContext.Provider>     ) } export default AuthState;                      

In the code cake above, we wrote the function checkAuthenticationStatus(). In our function, here'due south what we are doing:

  • We used the await keyword to get our token from AsyncStorage. With AsyncStorage, if at that place'south no token supplied, information technology returns zilch. Our initial userToken state is set to null also.
  • We utilize the setUserToken to set our returned value from AsyncStorage every bit our new userToken. If the returned value is null, it ways our userToken remains cipher.
  • Later on the try{}…catch(){} block, we set isLoading to fake because the office to check authentication status is complete. We'll need the value of isLoading to know if we should still be displaying the TransitionScreen or non. Information technology's worth considering setting an error if in that location is an error retrieving the token so that we can show the user a "Retry" or "Try Again" button when the mistake is encountered.
  • Whenever AuthState mounts nosotros want to check the authentication status, so we utilize the useEffect() ReactJS claw to do this. We call our checkAuthenticationStatus() part inside the useEffect() hook and set the value of isLoading to imitation when it is done.
  • Finally, nosotros add our states to our <AuthContext.Provider/> values so that we tin admission them from anywhere in our app covered by the Context API.

Now that we accept our role, it is time to get back to our AppNavigator.js and write the lawmaking for mounting a item stack navigator based on the authentication status:

navigation > AppNavigator.js

Starting time, we will import all nosotros need for our AppNavigator.js.

            import React, { useEffect, useContext } from "react"; import PreAuthNavigator from "./preAuthNavigator"; import PostAuthNavigator from "./postAuthNavigator"; import { NavigationContainer } from "@react-navigation/native" import { createStackNavigator } from "@react-navigation/stack"; import AuthContext from "../../context/authContext/AuthContext"; import TransitionScreen from "../screens/TransitionScreen";                      

Now that we have all our imports, let's create the AppNavigator() part.

          ... const AppNavigator = () => {  }  consign default AppNavigator                  

Next, we will at present go ahead to write the content of our AppNavigator() function:

            import React, { useState, useEffect, useContext } from "react"; import PreAuthNavigator from "./preAuthNavigator"; import PostAuthNavigator from "./postAuthNavigator"; import { NavigationContainer } from "@react-navigation/native" import { createStackNavigator } from "@react-navigation/stack"; import AuthContext from "../../context/authContext/AuthContext"; import TransitionScreen from "../screens/transition";  const AppNavigator = () => {     const { Navigator, Screen } = createStackNavigator();     const authContext = useContext(AuthContext);     const { userToken, isLoading } = authContext;     if(isLoading) {       render <TransitionScreen />     }     return (     <NavigationContainer>       <Navigator>         {            userToken == zip ? (             <Screen               name="PreAuth"               component={PreAuthNavigator}               options={{ header: () => nada }}             />           ) : (             <Screen                name="PostAuth"               component={PostAuthNavigator}               options={{ header: () => null }}             />           )         }       </Navigator>     </NavigationContainer>   ) }  export default AppNavigator                      

In the in a higher place block of code, here'south an outline of what nosotros did:

  • We created a stack navigator and destructured the Navigator and Screen from it.
  • Nosotros imported the userToken and the isLoading from our AuthContext
  • When the AuthState mounts, the checkAuthenticationStatus() is called in the useEffecct hook there. We use the if statement to check if isLoading is truthful, if it is true the screen we return is our <TransitionScreen /> which nosotros created before because the checkAuthenticationStatus() office is not still complete.
  • Once our checkAuthenticationStatus() is consummate, isLoading is gear up to faux and we render our main Navigation components.
  • The NavigationContainer was imported from the @react-navigation/native. It is simply used in one case in the chief top-level navigator. Notice that we are not using this in the preAuthNavigator.js or the postAuthNavigator.js.
  • In our AppNavigator(), we still create a stack navigator. If the userToken gotten from our Context API is null, we mount the PreAuthNavigator, if its value is something else (meaning that the AsyncStorage.getItem() in the checkAuthenticationStatus() returned an actual value), and so nosotros mountain the PostAuthNavigator. Our conditional rendering is done using the ternary operator.

Now we've set up up our AppNavigator.js. Next, we need to laissez passer our AppNavigator into our App.js file.

Let'southward pass our AppNavigator into the App.js file:

App.js

                      ... import AppNavigator from './views/navigation/AppNavigator';  ... return (     <AuthState>       <AppNavigator />     </AuthState>   );                  

Let'south now encounter what our app looks like at the moment:

Hither's what happens when y'all supply an incorrect credential while trying to log in:

Adding The Logout Functionality

At this point, our authentication and route selection procedure is consummate. The simply matter left for our app is to add the logout functionality.

The logout button is in the HomeScreen.js file. Nosotros passed an onLogout() function to the onPress aspect of the button. For now, we accept a elementary console.log() statement in our function, only in a petty while that will change.

At present, let'southward go to our AuthState.js and write the part for logout. This role simply clears the AsyncStorage where the user token is saved.

context > authContext > AuthState.js

          ... const AuthState = (props) => {     ...      const userSignout = async() => {         wait AsyncStorage.removeItem('user-token');         setUserToken(null);     }       return (       ...     ) }  export default AuthState;                  

The userSignout() is an asynchronous role that removes the user-token from our AsyncStorage.

Now nosotros need to phone call the userSignout() role in our HomeScreen.js any time the logout push is clicked on.

Let's become to our HomeScreen.js and use ther userSignout() from our AuthContext.

screens > postAuthScreens > HomeScreen.js

            import React, { useContext } from 'react'; import { View, Text, Button, StyleSheet } from 'react-native'; import AuthContext from '../../../context/authContext/AuthContext'  const HomeScreen = () => {   const { userSignout } = useContext(AuthContext)      const onLogout = () => {     userSignout()   }   return (     <View fashion={styles.container}>       <Text>Now you're authenticated! Welcome!</Text>  <Button title="LOG OUT" onPress={onLogout} />     </View>   ) } ...                      

In the higher up code block nosotros imported thee useContext hook from ReactJS, then we imported our AuthContext. Next, we destructured the userSignout function from our AuthContext and this userSignout() function is called in our onLogout() function.

Now whenever our logout button is clicked, the user token in our AsyncStorage is cleared.

Voila! our entire procedure is finished.

Here's what happens when you press the back push after you're logged in:

Pressing the back button after logging into the app.

Here's what happens when y'all printing the dorsum button after logging out:

Pressing the back push button subsequently logging out of the app.

Hither are some different behaviors we discover when using this design in our navigation stack switching:

  1. You lot'll discover that there was nowhere we needed to make use of navigation.navigate() or navigation.push() to get to another route after login. Once our state is updated with the user token, the navigation stack rendered is automatically changed.
  2. Pressing the dorsum push button on your device after login is successful cannot take y'all back to the login page, instead, it closes the app entirely. This behavior is important because you don't want the user to be able to render back to the login page except they log out of the app. The same thing applies to logging out — once the user logs out, they cannot use the back button to return to the HomeScreen screen, only instead, the app closes.

Conclusion

In many Apps, authentication is 1 of the most important parts considering it confirms that the person trying to gain access to protected content has the right to admission the data. Learning how to practice it correct is an important step in building a great, intuitive, and like shooting fish in a barrel to use/navigate the awarding.

Building on top of this code, here are a few things you lot might consider calculation:

  • Form validation for validating input fields. Bank check out React Native form validation with Formik and Yup.
  • Firebase authentication for integrating authentication with Gmail, Github, Facebook, Twitter, or your custom interface. Bank check out React Native Firebase.
  • Code concepts for designers: Authentication and Authorization.

Here are too some important resources I found that will enlighten you more about authentication, security and how to do information technology right:

Resources

  • React Native: User Hallmark Flow Explained
  • 10 React Security All-time Practices
  • Authentication Methods That Can Forbid The Next Breach
  • View a live build/preview of our application hither;
  • View the project on GitHub.

Smashing Editorial (ks, vf, yk, il)

palmatierstriging.blogspot.com

Source: https://www.smashingmagazine.com/2021/08/mounting-unmounting-navigation-routes-react-native/

0 Response to "Stacknavigator React Native Goes to Screen Then Back Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel