I am experiencing an issue with navigation in my React Native application. Here is the relevant part of my RootNavigator component:
const Stack = createStackNavigator();
export function RootNavigator() {
const isAuthenticated = useAppStore(state => state.isAuthenticated);
return (
<Stack.Navigator
initialRouteName={isAuthenticated ? 'home' : 'onBoard'}>
{!isAuthenticated ? (
<Stack.Screen
name="onBoard"
component={OnBoard}
options={{ headerShown: false }}
/>
) : (
<Stack.Screen
name="home"
component={Home}
options={{ headerShown: false }}
/>
)}
</Stack.Navigator>
);
}
When a user logs in successfully, I update the isAuthenticated state and navigate to the home screen like this:
setIsAuthenticated(true);
navigation.navigate('home');
However, even though the isAuthenticated state changes to true, the data inside Stack.Navigator doesn’t seem to be updated and navigation to the home screen fails with an error stating that it can’t find the home screen.
Interestingly, if I restart the app after logging in, it navigates to the home screen correctly. This suggests that the navigation structure is correct, but the stack is not dynamically updating.
Can someone help me understand why Stack.Navigator is not updating correctly and how I can fix this problem?
Here I expect it to go to the home screen when setIsAuthenticated(true); is done.