I\'m using react native navigation (react-navigation) StackNavigator. it starts from the Login page throughout the whole lifecycle of the app. I don\'t want to have a back
The best option to handle this situation is to use SwitchNavigator provided by React navigation. The purpose of SwitchNavigator is to only ever show one screen at a time. By default, it does not handle back actions and it resets routes to their default state when you switch away. This is the exact behavior that is needed in the authentication flow.
This is a typical way to implement it.
Here is a code implementation of above statements
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import HomeScreen from "./homeScreenPath"
import OtherScreen from "./otherScreenPath"
import SignInScreen from "./SignInScreenPath"
import SplashScreen from "./SplashScreenPath"
const AppStack = createStackNavigator({ Home: HomeScreen, Other: OtherScreen });
const AuthStack = createStackNavigator({ SignIn: SignInScreen });
export default createAppContainer(
createSwitchNavigator(
{
Splash: SplashScreen,
App: AppStack,
Auth: AuthStack,
},
{
initialRouteName: 'Splash',
}
)
);
Now in SplashScreen you will check the token and navigate accordingly
import React from 'react';
import {
ActivityIndicator,
AsyncStorage,
StatusBar,
StyleSheet,
View,
} from 'react-native';
class SplashScreen extends React.Component {
componentDidMount() {
this.checkIfLogin();
}
// Fetch the token from storage then navigate to our appropriate place
checkIfLogin = async () => {
const userToken = await AsyncStorage.getItem('userToken');
// This will switch to the App screen or Auth screen and this splash
// screen will be unmounted and thrown away.
this.props.navigation.navigate(userToken ? 'App' : 'Auth');
};
// Render any loading content that you like here
render() {
return (
);
}
}
Once you change routes in SwitchNavigator it removes the older route automatically and hence if you press the back button it will not take you to the auth/login screens anymore