3
votes

I'm building an app using react-native and stack navigators, and tab navigators. Screens never unmounts when navigating. I want to unmount the screens when a user press a 'logout' button, so when a new user logs in all screens need to be mounted again without old state preservation.

How can I do this? Using this.props.navigation.popToTop() inside a screen does not work.

My current navigators structure:

App DrawerNavigator -> OnBoard Drawer Navigator --> (SignIn screen, SignUp screen)
                    -> Logged Drawer Navigaror --> Home Tab Navigator
                                               --> Settings Stack Navigator -->(Settings screen)

I'm calling the logout function inside the Settings screen.

3

3 Answers

4
votes

Could you try this??

import { StackActions } from 'react-navigation'; // before
import { StackActions } from '@react-navigation/native'; // current

this.props.navigation.dispatch(StackActions.popToTop());
2
votes

This will reset whole router and put you on one single screen,

const resetAction = StackActions.reset({ // import StackActions & NavigationActions from react-navigation
  index: 0,
  key: null, // this is important
  actions: [NavigationActions.navigate({ routeName: "ScreenName" })] // where you want to go after reset
});
this.props.navigation.dispatch(resetAction);

if StackActions or NavigationActions are undefined then you might be using it under other navigations like drawer or tab. Move this reset code into stack or switch router screen.

1
votes

Finally, I got the answer. Might be helpful to those who are stuck in the same problem. The main Navigator must be configured as a SwithNavigator. From docs:

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 we want from the authentication flow: when users sign in, we want to throw away the state of the authentication flow and unmount all of the screens, and when we press the hardware back button we expect to not be able to go back to the authentication flow. We switch between routes in the SwitchNavigator by using the navigate action

so, our app needs to be created as following:

const AppNavigator = createSwitchNavigator(
    {
        OnBoard: OnBoardTabsNavigator,
        Logged: LoggedDrawerNavigator,
    }
);

then, in the logout screen, configure the following logout function:

_LogOut(){
    console.log("Logging out");
    AsyncStorage.clear() // <-- Don't forget to clear any variables stored on Async Storage
    .then(() => {
        this.props.navigation.navigate('SignIn')
    })
    .catch((err) => {
        console.log(err);
    })
}