Dealing with Mounting And Unmounting Of Navigation Routes In React Native

No Comments

On this article, we’re going to stroll by way of mounting and unmounting of navigation routes in React Native. An anticipated habits of your app is that when the authentication situation is met, a brand new set of navigation routes can be found solely to logged-in customers, whereas the opposite screens which have been displayed earlier than authentication is eliminated and may’t be returned to except the consumer indicators out of the applying.

For safety in your app, protected routes give you a technique to solely show sure info/content material in your app to particular customers, whereas limiting entry from unauthorized individuals.

We will probably be working with Expo for this venture as a result of it’ll assist us deal with the issue at hand as an alternative of worrying about plenty of setups. The very same steps on this article might be adopted for a naked React Native utility.

You want some familiarity with JavaScript and React Native to observe by way of with this tutorial. Listed here are a couple of necessary issues you need to already be aware of:

Customized parts in React Native ( create parts, obtain, move, and use props in a part). Learn extra.
React Navigation. Learn extra.
Stack Navigator in React Native. Learn extra.
Primary Data of React Native Core parts (<View/>, <Textual content/>, and so on.). Learn extra.
React Native AsyncStorage. Learn extra.
Context API. Learn extra.

Venture Setup And Base Authentication

In the event you’re new to utilizing expo and don’t know set up expo, go to the official documentation. As soon as the set up is full, go forward to initialize a brand new React Native venture with expo from our command immediate:

expo init navigation-project

You can be offered with some choices to decide on the way you need the bottom setup to be:

In our case, let’s choose the primary choice to arrange our venture as a clean doc. Now, wait till the set up of the JavaScript dependencies is full.

As soon as our app is about up, we will change our listing to our new venture listing and open it in your favourite code editor. We have to set up the library we will probably be utilizing for AsyncStorage and our navigation libraries. Inside your folder listing in your terminal, paste the command above and select a template (clean would work) to put in our venture dependencies.

Let us take a look at what every of those dependencies is for:

@react-native-community/async-storage
Like localStorage on the net, it’s a React Native API for persisting knowledge on a tool in key-value pairs.
@react-native-community/masked-view, react-native-screens, react-native-gesture-handle
These dependencies are core utilities which can be utilized by most navigators to create the navigation construction within the app. (Learn extra in Getting began with React Native navigation.)
@react-navigation/native
That is the dependency for React Native navigation.
@react-navigation/stack
That is the dependency for stack navigation in React Native.

npm set up @react-native-community/async-storage @react-native-community/masked-view @react-navigation/native @react-navigation/stack react-native-screens react-native-gesture-handle

To begin the applying use expo begin from the app listing in your terminal. As soon as the app is began, you should utilize the expo app out of your cell phone to scan the bar code and look at the applying, or in case you have an android emulator/IOS simulator, you may open the app by way of them from the expo developer instrument that opens up in your browser while you begin an expo utility. For the photographs examples on this article, we will probably be utilizing Genymotions to see our consequence. Right here’s what our last consequence will seem like in Genymotions:

Folder Buildings

Allow us to create our folder construction from the beginning in order that it is simpler for us to work with it as we proceed:

We’d like two folders first:

context
This folder will maintain the context for our whole utility as we will probably be working with Context API for international state administration.
views
This folder will maintain each the navigation folder and the views for various screens.

Go forward and create the 2 folders in your venture listing.

Contained in the context folder, create a folder referred to as authContext and create two file within the authContext folder:

AuthContext.js,
AuthState.js.

We are going to want these recordsdata once we begin working with Context API.

Now go to the views folder we created and create two extra folders within it, specifically:

navigation,
screens.

Now, we’re not but completed, contained in the screens folder, create these two extra folders:

postAuthScreens,
preAuthScreens.

In the event you adopted the folder setup accurately, that is how your folder construction ought to seem like in the meanwhile:

Creating Our First Display screen

Now let’s create our first display and name it the welcomeScreen.js contained in the preAuthScreens folder.

preAuthScreens > welcomeScreen.js

Right here’s the content material of our welcomeScreen.js file:

import React from ‘react’;
import { View, Textual content, Button, StyleSheet, TextInput } from ‘react-native’;

const WelcomeScreen = () => {

const onUserAuthentication = () => {
console.log(“Person authentication button clicked”)
}

return (
<View model={kinds.container}>
<Textual content model={kinds.header}>Welcome to our App!</Textual content>
<View>
<TextInput model={kinds.inputs} placeholder=”Enter your e-mail right here..” />
<TextInput model={kinds.inputs} secureTextEntry={true} placeholder=”Enter your password right here..” />
<Button title=”AUTHENTICATE” onPress={onUserAuthentication} />
</View>
</View>
)
}

const kinds = StyleSheet.create({
container: {
flex: 1,
backgroundColor: ‘#fff’,
alignItems: ‘middle’,
justifyContent: ‘middle’,
},
header: {
fontSize: 25,
fontWeight: ‘daring’,
marginBottom: 30
},
inputs: {
width: 300,
top: 40,
marginBottom: 10,
borderWidth: 1,
}
})

export default WelcomeScreen

This is what we did within the code block above:

First, we imported the issues we’d like from the React Native library, specifically, View, Textual content, Button, TextInput. Subsequent, we created our practical part WelcomeScreen.

You’ll discover that we imported the StyleSheet from React Native and used it to outline kinds for our header and likewise our <TextInput />.

Lastly, we export the WelcomeScreen part on the backside of the code.

Now that we’re achieved with this, let’s get this part to perform as anticipated through the use of the useState hook to retailer the values of the inputs and replace their states anytime a change occurs within the enter fields. We may also deliver import the useCallback hook from React as we will probably be needing it later to carry a perform.

First, whereas we’re nonetheless within the WelcomeScreen part, we have to import the useState and useCallback from React.

import React, { useState, useCallback } from ‘react’;

Now contained in the WelcomeScreen practical part, let’s create the 2 states for the e-mail and password respectively:


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

)
}

Subsequent, we have to modify our <TextInput /> fields in order that the get their worth from their respective states and replace their state when the worth of the enter is up to date:

import React, { useState, useCallback } from ‘react’;
import { View, Textual content, Button, StyleSheet, TextInput } from ‘react-native’;

const WelcomeScreen = () => {
const [email, setEmail] = useState(”)
const [password, setPassword] = useState(”)

const onInputChange = (worth, setState) => {
setState(worth);
}
return (
<View>

<View>
<TextInput
model={kinds.inputs}
placeholder=”Enter your e-mail right here..”
worth={e-mail}
onChangeText={(worth) => onInputChange(worth, setEmail)}
/>
<TextInput
model={kinds.inputs}
secureTextEntry={true}
placeholder=”Enter your password right here..”
worth={password}
onChangeText={(worth) => onInputChange(worth, setPassword)}
/>

</View>
</View>
)
}

Within the code above, here’s what we did:

We made the worth of every of the textual content inputs to level to their respective states.
We added the onChangeText handler to our textual content inputs. This fires up anytime a brand new worth is entered or deleted from the enter fields.
We referred to as our onInputChange perform which accepts two arguments:
The present worth is provided by the onChangeText handler.
The setter of the state that needs to be up to date (for the primary enter discipline we move setEmail and the second we move setPassword.
Lastly, we write our onInputChange perform, and our perform does just one factor: It updates the respective states with the brand new worth.

The subsequent factor we have to work on is the onUserAuthentication() perform with is known as each time the button for the shape submission is clicked.

Ideally, the consumer will need to have already created an account and login will contain some backend logic of some type to verify that the consumer exists after which assign a token to the consumer. In our case, since we’re not utilizing any backend, we are going to create an object holding the right consumer login element, after which solely authenticate a consumer when the values they enter matches our mounted values from the login object of e-mail and password that we’ll create.

Right here’s the code we have to do that:

const correctAuthenticationDetails = {
e-mail: ‘demouser@gmail.com‘,
password: ‘password’
}
const WelcomeScreen = () => {

// This perform will get referred to as when the AUTHENTICATE button is clicked
const onUserAuthentication = () => {
if (
e-mail !== correctAuthenticationDetails.e-mail ||
password !== correctAuthenticationDetails.password
) {
alert(‘The e-mail or password is wrong’)
return
}
// In right here, we are going to deal with what occurs if the login particulars are // appropriate
}


return (

)
}

One of many first belongings you’ll discover within the code above is that we outlined a correctAuthenticationDetails (which is an object that holds the right login particulars we anticipate a consumer to produce) exterior of the WelcomeScreen() practical part.

Subsequent, we wrote the content material of the onUserAuthentication() perform and used a conditional assertion to verify if the e-mail or password held within the respective states doesn’t match the one we provided in our object.

If you need to see what we’ve got achieved to this point, import the WelcomeScreen part into your App.js like this:

Open the App.js file and put this exchange all the 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 perform App() {
return (
<View>
<StatusBar model=”auto” />
<WelcomeScreen />
</View>
);
}

Wanting intently on the code above, you’ll see that what we did was import the WelcomeScreen part after which used it within the App() perform.

Right here’s what the consequence seems like of our WelcomeScreen seems like:

Now that we’re achieved constructing the WelcomeScreen part, let’s transfer forward and begin working with Context API for managing our international state.

Why Context API?

Utilizing Context API, we don’t want to put in any extra library into ReactJS, it’s much less annoying to arrange, and is likely one of the hottest methods of dealing with international state in ReactJS. For light-weight state administration, it’s a sensible choice.

Creating Our Context

In the event you recall, we created a context folder earlier and created a subfolder within it referred to as the authContext.

Now let’s navigate to the AuthContext.js file within 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 simply created holds the loading state worth and the userToken state values. At the moment, within the createContext we declared within the code-block above, we didn’t initialize any default values right here so our context is at present undefined. An instance worth of the auth context might be {loading: false, userToken: ‘abcd}

The AuthState.js file holds our Context API logic and their state values. Capabilities written right here will be referred to as from wherever in our app and once they replace values in state, it’s up to date globally additionally.

First, let’s usher in all of the imports we are going to want on this file:

context > AuthContext > AuthState.js

import React, { useState } from ‘react’;
import AuthContext from ‘./AuthContext’;
import AsyncStorage from ‘@react-native-community/async-storage’;

We imported the useState() hook from ReactJS to carry our states, we imported the AuthContext file we created above as a result of that is the place our empty context for authentication is initialized and we might want to use it as you’ll see afterward whereas we progress, lastly we import the AsyncStorage bundle (just like localStorage for the net).

AsyncStorage is a React Native API that lets you persist knowledge offline over the gadget in a React Native utility.

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);
console.warn(“consumer has been authenticated!”)
}

return (
<AuthContext.Supplier
worth={{
onAuthentication,
}}
>
{props.kids}
</AuthContext.Supplier>
)
}
export default AuthState;

Within the code block above here is what we did:

We declared two states for the userToken and isLoading. The userToken state will probably be used to retailer the token saved to AsyncStorage, whereas the isLoading state will probably be used to trace the loading standing (initially it’s set to true). We are going to discover out extra about using these two states as we proceed.

Subsequent, we wrote our onAuthentication() perform. This perform is an async perform that will get referred to as when the login button is clicked from the welcomeScreen.jsx file. This perform will solely get referred to as if the e-mail and password the consumer has provided matches the right consumer element object we supplied. Normally what occurs throughout authentication is {that a} token is generated for the consumer after the consumer is authenticated on the backend utilizing a bundle like JWT, and this token is shipped to the frontend. Since we’re not going into all of that for this tutorial, we created a static token and stored it in a variable referred to as USER_TOKEN.

Subsequent, we use the await key phrase to set our consumer token to AsyncStorage with the identify user-token. The console.warn() assertion is simply used to verify that all the pieces went proper, you may take it off everytime you like.

Lastly, we move our onAuthenticated perform as a price inside our <AuthContext.Supplier> in order that we will entry and name the perform from wherever in our app.

screens > preAuth > welcomeScreen.js

First, 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, contained in the welcomeScreen() practical part, let’s use the context which we’ve got created:


const WelcomeScreen = () => {
const { onAuthentication } = useContext(AuthContext)
const onUserAuthentication = () => {
if (
e-mail !== correctAuthenticationDetails.e-mail ||
password !== correctAuthenticationDetails.password
) {
alert(‘The e-mail or password is wrong’)
return
}
onAuthentication()
}
return (

)
}

Within the above code block, we destructured the onAuthentication perform from our AuthContext after which we referred to as it inside our onUserAuthentication() perform and eliminated the console.log() assertion which was there prior to now.

Proper now, this can throw an error as a result of we don’t but have entry to the AuthContext. To make use of the AuthContext wherever in your utility, we have to wrap the top-level file in our app with the AuthState (in our case, it’s the App.js file).

Go to the App.js file and exchange the code there with this:

import React from ‘react’;
import WelcomeScreen from ‘./views/screens/preAuthScreens/welcomeScreen’;
import AuthState from ‘./context/authContext/AuthState’

export default perform App() {
return (
<AuthState>
<WelcomeScreen />
</AuthState>
);
}

We have come to this point and we’re achieved with this part. Earlier than we transfer into the subsequent part the place we arrange our routing, let’s create a brand new display. The display we’re about to create would be the HomeScreen.js file which is meant to point out up solely after profitable authentication.

Go to: screens > postAuth.

Create a brand new file referred to as HomeScreen.js. This is the code for the HomeScreen.js file:

screens > postAuth > HomeScreen.js

import React from ‘react’;
import { View, Textual content, Button, StyleSheet } from ‘react-native’;

const HomeScreen = () => {

const onLogout = () => {
console.warn(“Logout button cliked”)
}

return (
<View model={kinds.container}>
<Textual content>Now you are authenticated! Welcome!</Textual content>
<Button title=”LOG OUT” onPress={onLogout} />
</View>
)
}

const kinds = StyleSheet.create({
container: {
flex: 1,
backgroundColor: ‘#fff’,
alignItems: ‘middle’,
justifyContent: ‘middle’,
},
})

export default HomeScreen

For now, the logout button has a dummy console.log() assertion. In a while, we are going to create the logout performance and move it to the display from our context.

Setting Up Our Routes

We have to create three (3) recordsdata inside our navigation folder:

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

When you’ve created these three recordsdata, navigate to the preAuthNaviagtor.js file you simply 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, Display screen } = createStackNavigator();

return (
<Navigator initialRouteName=”Welcome”>
<Display screen
identify=”Welcome”
part={WelcomeScreen}
/>
</Navigator>
)
}
export default PreAuthNavigator;

Within the file above, here is what we did:

We imported the createStackNavigator from the @react-navigation/stack which we’re utilizing for our stack navigation. The createStackNavigatorProvides a manner to your app to transition between screens the place every new display is positioned on high of a stack. By default the stack navigator is configured to have the acquainted iOS and Android look & really feel: new screens slide in from the appropriate on iOS, fade in from the underside on Android. Click on right here if you wish to be taught extra concerning the stack navigator in React Native.
We destructured Navigator and Display screen from the createStackNavigator().
In our return assertion, we created our navigation with the <Navigator/> and created our display with the <Display screen/>. which means that if we had a number of screens that may be accessed earlier than authentication, we may have a number of <Display screen/> tags right here representing them.
Lastly, we export our PreAuthNavigator part.

Allow us to do an analogous factor 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, Display screen} = createStackNavigator();
return (
<Navigator initialRouteName=”House”>
<Display screen
identify=”House”
part={HomeScreen}
/>
</Navigator>
)
}
export default PostAuthNavigator;

As we see within the code above, the one distinction between the preAuthNavigator.js and the postAuthNavigator.js is the display being rendered. Whereas the primary one takes the WelcomeScreen, the postAuthNavigator.js takes the HomeScreen.

To create our AppNavigator.js we have to create a couple of issues.

For the reason that AppNavigator.js is the place we will probably be switching and checking which route will probably be obtainable for entry by the consumer, we’d like a number of screens in place for this to work correctly, let’s define the issues we have to create first:

TransitionScreen.js
Whereas the app decides which navigation it’s going to mount, we wish a transition display to point out up. Usually, the transition display will probably be a loading spinner or some other customized animation chosen for the app, however in our case, we are going to use a fundamental <Textual content/> tag to show loading….
checkAuthenticationStatus()
This perform is what we will probably be calling to verify the authentication standing which is able to decide which navigation stack goes to be mounted. We are going to create this perform in our context and use it within the Appnavigator.js.

Now, let’s go forward and create our TransitionScreen.js file.

screens > TransitionScreen.js

import React from ‘react’;
import { Textual content, View } from ‘react-native’;

const TransitionScreen = () => {
return (
<View>
<Textual content>Loading…</Textual content>
</View>
)
}

export default TransitionScreen

Our transition display is only a easy display that exhibits loading textual content. We are going to see the place to make use of this as we proceed on this article.

Subsequent, allow us to 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(null);
const [isLoading, setIsLoading] = useState(true);


useEffect(() => {
checkAuthenticationStatus()
}, [])

const checkAuthenticationStatus = async () => {
strive {
const returnedToken = await AsyncStorage.getItem(‘user-toke n’);
setUserToken(returnedToken);
console.warn(‘Person token set to the state worth)
} catch(err){
console.warn(This is the error that occured whereas retrievin g token: ${err})
}
setIsLoading(false)
}

const onAuthentication = async() => {

}

return (
<AuthContext.Supplier
worth={{
onAuthentication,
userToken,
isLoading,
}}
>
{props.kids}
</AuthContext.Supplier>
)
}
export default AuthState;

Within the code block above, we wrote the perform checkAuthenticationStatus(). In our perform, here is what we’re doing:

We used the await key phrase to get our token from AsyncStorage. With AsyncStorage, if there’s no token provided, it returns null. Our preliminary userToken state is about to null additionally.
We use the setUserToken to set our returned worth from AsyncStorage as our new userToken. If the returned worth is null, it means our userToken stays null.
After the strive{}…catch(){} block, we set isLoading to false as a result of the perform to verify authentication standing is full. We’ll want the worth of isLoading to know if we should always nonetheless be displaying the TransitionScreen or not. It’s value contemplating setting an error if there may be an error retrieving the token in order that we will present the consumer a “Retry” or “Attempt Once more” button when the error is encountered.
Each time AuthState mounts we need to verify the authentication standing, so we use the useEffect() ReactJS hook to do that. We name our checkAuthenticationStatus() perform contained in the useEffect() hook and set the worth of isLoading to false when it’s achieved.
Lastly, we add our states to our <AuthContext.Supplier/> values in order that we will entry them from wherever in our app lined by the Context API.

Now that we’ve got our perform, it’s time to return to our AppNavigator.js and write the code for mounting a selected stack navigator primarily based on the authentication standing:

navigation > AppNavigator.js

First, we are going to import all we’d like 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’ve got all our imports, let’s create the AppNavigator() perform.


const AppNavigator = () => {

}

export default AppNavigator

Subsequent, we are going to now go forward to write down the content material of our AppNavigator() perform:

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, Display screen } = createStackNavigator();
const authContext = useContext(AuthContext);
const { userToken, isLoading } = authContext;
if(isLoading) {
return <TransitionScreen />
}
return (
<NavigationContainer>
<Navigator>
{
userToken == null ? (
<Display screen
identify=”PreAuth”
part={PreAuthNavigator}
choices={{ header: () => null }}
/>
) : (
<Display screen
identify=”PostAuth”
part={PostAuthNavigator}
choices={{ header: () => null }}
/>
)
}
</Navigator>
</NavigationContainer>
)
}

export default AppNavigator

Within the above block of code, here is a top level view of what we did:

We created a stack navigator and destructured the Navigator and Display screen from it.
We imported the userToken and the isLoading from our AuthContext
When the AuthState mounts, the checkAuthenticationStatus() is known as within the useEffecct hook there. We use the if assertion to verify if isLoading is true, whether it is true the display we return is our <TransitionScreen /> which we created earlier as a result of the checkAuthenticationStatus() perform is just not but full.
As soon as our checkAuthenticationStatus() is full, isLoading is about to false and we return our primary Navigation parts.
The NavigationContainer was imported from the @react-navigation/native. It’s only used as soon as in the primary top-level navigator. Discover that we’re not utilizing this within the preAuthNavigator.js or the postAuthNavigator.js.
In our AppNavigator(), we nonetheless create a stack navigator. If the userToken gotten from our Context API is null, we mount the PreAuthNavigator, if its worth is one thing else (that means that the AsyncStorage.getItem() within the checkAuthenticationStatus() returned an precise worth), then we mount the PostAuthNavigator. Our conditional rendering is completed utilizing the ternary operator.

Now we’ve arrange our AppNavigator.js. Subsequent, we have to move our AppNavigator into our App.js file.

Let’s move our AppNavigator into the App.js file:

App.js


import AppNavigator from ‘./views/navigation/AppNavigator’;


return (
<AuthState>
<AppNavigator />
</AuthState>
);

Let’s now see what our app seems like in the meanwhile:

Right here’s what occurs while you provide an incorrect credential whereas making an attempt to log in:

Including The Logout Performance

At this level, our authentication and route choice course of is full. The one factor left for our app is so as to add the logout performance.

The logout button is within the HomeScreen.js file. We handed an onLogout() perform to the onPress attribute of the button. For now, we’ve got a easy console.log() assertion in our perform, however in a short time that can change.

Now, let’s go to our AuthState.js and write the perform for logout. This perform merely clears the AsyncStorage the place the consumer token is saved.

context > authContext > AuthState.js


const AuthState = (props) => {

const userSignout = async() => {
await AsyncStorage.removeItem(‘user-token’);
setUserToken(null);
}

return (

)
}

export default AuthState;

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

Now we have to name the userSignout() perform in our HomeScreen.js any time the logout button is clicked on.

Let’s go to our HomeScreen.js and use ther userSignout() from our AuthContext.

screens > postAuthScreens > HomeScreen.js

import React, { useContext } from ‘react’;
import { View, Textual content, Button, StyleSheet } from ‘react-native’;
import AuthContext from ‘../../../context/authContext/AuthContext’

const HomeScreen = () => {
const { userSignout } = useContext(AuthContext)

const onLogout = () => {
userSignout()
}
return (
<View model={kinds.container}>
<Textual content>Now you are authenticated! Welcome!</Textual content>
<Button title=”LOG OUT” onPress={onLogout} />
</View>
)
}

Within the above code block we imported thee useContext hook from ReactJS, then we imported our AuthContext. Subsequent, we destructured the userSignout perform from our AuthContext and this userSignout() perform is known as in our onLogout() perform.

Now each time our logout button is clicked, the consumer token in our AsyncStorage is cleared.

Voila! our whole course of is completed.

Right here’s what occurs while you press the again button after you’re logged in:

Right here’s what occurs while you press the again button after logging out:

Listed here are some totally different behaviors we discover when utilizing this sample in our navigation stack switching:

You’ll discover that there was nowhere we wanted to utilize navigation.navigate() or navigation.push() to go to a different route after login. As soon as our state is up to date with the consumer token, the navigation stack rendered is robotically modified.
Urgent the again button in your gadget after login is profitable can’t take you again to the login web page, as an alternative, it closes the app completely. This habits is necessary since you don’t need the consumer to have the ability to return again to the login web page besides they log off of the app. The identical factor applies to logging out — as soon as the consumer logs out, they can’t use the again button to return to the HomeScreen display, however as an alternative, the app closes.

Conclusion

In lots of Apps, authentication is likely one of the most necessary elements as a result of it confirms that the individual making an attempt to realize entry to protected content material has the appropriate to entry the data. Studying do it proper is a crucial step in constructing a fantastic, intuitive, and straightforward to make use of/navigate the applying.

Constructing on high of this code, right here are some things you may contemplate including:

Kind validation for validating enter fields. Try React Native type validation with Formik and Yup.
Firebase authentication for integrating authentication with Gmail, Github, Fb, Twitter, or your customized interface. Try React Native Firebase.
Code ideas for designers: Authentication and Authorization.

Listed here are additionally some necessary assets I discovered that can enlighten you extra about authentication, safety and do it proper:

Sources

React Native: Person Authentication Circulate Defined
10 React Safety Greatest Practices
Authentication Strategies That Can Stop The Subsequent Breach
View a dwell construct/preview of our utility right here;
View the venture on GitHub.

    About Marketing Solution Australia

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment