Max
Max

Reputation: 325

Tab Navigator is not resetting when user signs out in react-native app

I am currently implementing authentication flow into my react-native app. I have an AppNavigator(bottom-tabs-navigator) and an AuthNavigator (stack-navigator). In my App.js I have a navigationContainer, and I check to see if a user currently exists, based on if an auth token is stored in the phone. I then render the proper navigator depending on if there is a token or not.

<NavigationContainer ref={navigationRef} theme={MyTheme}>
  {!user ? (
    <AuthNavigator />
  ) : (
    <AppTabNavigator />
  )}
</NavigationContainer>

When the user signs out I simply remove the token and set the user variable to null.

  const signout = () => {
    authStorage.removeToken();
    setUser(null);
  };

This is all working fine, the user is able to sign in and out, and the proper navigator is rendered. However, the problem is that if the user signs out, and then signs back in (either as the same user or a different one), the first tab/screen they see is the last screen in my TabNavigator. I have 5 tabs in my navigator and the user should be on the first tab when they sign in, but instead they are taken to the 5th tab. Even if I pass the "initialRouteName" prop to the navigator, it still goes directly to the 5th screen. This behavior does not occur the first time a user signs in however. It only occurs after signing out and then signing back in. This makes me believe that somehow the state of the navigator is persisting after the user signs out. The 5th tab is the profile tab and that is where the user signs out. So the 5th tab would be the last one visited before the user signs out. Thank you to anyone who can help!

Upvotes: 2

Views: 1458

Answers (2)

Max
Max

Reputation: 325

If anyone else comes across this problem, I think I found a good solution, at least for the time being. In the logout function, as suggested by D10S, I reset the navigation state before I setUser(null). And I actually removed the setUser() from the logout function entirely and added it in a useEffect cleanup for the screen component. So whenever the screen unmounts, the cleanup function checks to see if there is an auth token present. If there is no token, then the user is set to "null". Since logging out results in the token being removed, the user is then properly set. This solution seems to be working fine with expected behavior and no react-warnings.

Upvotes: 1

D10S
D10S

Reputation: 1549

On the "logout" function, right before you call "signout" try to reset the navigator state.
You can see more about reseting the navigator state here.

Upvotes: 0

Related Questions