Prevent user from going back to login screen after logging in successfully in React Native

I have 3 screens. A=>Login, B=>Dashboard, C=>Profile.

Initially when user is not logged in the Login screen renders. After login I have used AsyncStorage to save userId(which i get from API response). If user is logged in already and opens the application, I have redirected user to Dashboard page.

These are the problems i am facing with my code implementation.

  1. after login, if user press the back button on Dashboard page(Andriod), it navigates back to the login screen. and this time componentDidMount() method does not invoked so i am unable to put a check if the user has came from dashboard screen.
  2. I have tried to register BackHandler event on Dashboard's componentDinMount() method with condition => if user press back button, the application will exit, but problem is I am unable to remove this event on the same screen, so if I go to Profile screen from Dashboard, and from Profile page if i press backbutton, the application exits.

All I want to achieve is, After login, until the user presses logout button, user should not be able to go login screen.


Solution 1:

You can simply achieve this by using switch navigator instead of a stack navigator when navigating from 'Login screen' to 'Dashboard'.

const MainStack = createStackNavigator({
    DashboardScreen: Dashboard,
    ProfileScreen: Profile
});

export default createAppContainer(createSwitchNavigator({
  LoginScreen: Login,
  Main: MainStack
}));

Solution 2:

You need to reset your navigation history to do that

This is a snippet from one of my project where I needed to do the same:

this.props.navigation.reset([NavigationActions.navigate({ routeName: 'DevicesList'})], 0);