I have a React Native project that uses react-navigation v6. This is the navigation structure:
const { user } = userContext;
<NavigationContainer>
{user === null ? (
<AuthStack.Navigator
initialRouteName={"SignIn"}
screenOptions={{ headerShown: false }}
>
<AuthStack.Screen name="SignIn" component={SigninScr} />
<AuthStack.Screen name="SignUp" component={SignupScr} />
<AuthStack.Screen
name="EmailVerification"
component={EmailVerificationScr}
/>
</AuthStack.Navigator>
) : (
<Tab.Navigator
initialRouteName={'HomeStack'}
screenOptions={{ headerShown: false}}
>
<Tab.Screen name={'HomeStack'} children={()=><HomeStack />}/>
<Tab.Screen name={'DiscoverStack'} children={()=><DiscoverStack />}/>
<Tab.Screen name={'CalendarStack'} children={()=><CalendarStack />}/>
<Tab.Screen name={'ProfileStack'} children={()=><ProfileStack />}/>
</Tab.Navigator>
)}
</NavigationContainer>
Essentially, there are two stacks:
- Auth stack
- Signin screen, signup screen, etc...
- Regular stack
- 4 nested stacks (home stack, discover stack, calendar stack, profile stack)
I am using React Context to switch from the auth stack to the regular stack (or regular stack to auth stack)
The problem is that when the user logs off and signs back in, their stack was never reset and they are directed to the screen where they logged off. For example, user A logs in and goes to the profile screen, then they press log out. User A now logs back in, and instead of being sent to the home screen, they are sent back to the profile screen.
I want the navigation state of the regular stack to be reset when a user logs off. I have tried doing this, but it doesn't work (user still gets sent to the profile screen):
const { setUser } = this.context;
const { navigation } = this.props
navigation.reset({
index: 0,
routeNames: ['Home'],
routes: [{ name: 'Home' }],
});
setUser(null);
How can I completely reset the stack when switching stack for authentication flow?
For reference, this is what one of the stacks in the regular stack would look like:
const HomeStack = () => (
<Stack.Navigator screenOptions={{
headerTintColor: 'white',
headerTitleStyle: { color: 'white' },
headerStyle: { backgroundColor: colors.primary0 },
}}
>
<Stack.Screen name={'HomeScr'} component={HomeScr} />
...
</Stack.Navigator>
);

