'Why routes are loaded even the condition is not met in react navigation?
In my App.tsx I have set it up like this:
export default function App() {
const [user, setUser] = useState<any>(null);
return (
<Provider store={store}>
<NavigationContainer>
<AuthContext.Provider value={{user, setUser}}>
<SafeAreaView style={{flex: 1}}>
<Navigation />
</SafeAreaView>
</AuthContext.Provider>
</NavigationContainer>
</Provider>
);
}
My Navigation component contains the logic to render authenticated or non authenticated routes based on the user and it contains this:
const Navigation = () => {
const { user } = useContext(AuthContext);
return (
<Stack.Navigator>
{user ? (
<Stack.Group>
<Stack.Screen
name="Main"
component={Auth}
options={{
headerShown: false,
}}
/>
<Stack.Screen
name="Users"
component={Users}
options={{headerShown:false}}
/>
</Stack.Group>
) : (
<Stack.Screen
name="NonAuth"
component={NonAuth}
options={{ headerShown: false }}
/>
)}
</Stack.Navigator>
);
};
export default Navigation;
The Auth component is a BottomTabNavigator while the NonAuth is another StackNavigator
Inside the screens of the BottomTabNavigator I have a screen for settings and there lies the logout button, when I am clicking this button I am setting the user to null but I am getting the error saying:
null is not an object evaluating user.role
In the BottomTabNavigator I am checking the user.role to decide what bottom tabs to show but since the user is null why is it going inside the Auth routes, when I login it correctly goes from NonAuth to Auth automatically because on login I am setting the user to some data but on logout I set it to null and it still going inside the Auth?
These are the versions I am using:
"@react-navigation/bottom-tabs": "^6.0.9",
"@react-navigation/native": "^6.0.6",
"@react-navigation/native-stack": "^6.2.5",
"@react-navigation/stack": "^6.0.11",
Also note that the NonAuth is created using @react-navigation/native-stack
Navigation using @react-navigation/stack
Solution 1:[1]
Sounds like a race condition. user will eventually be null, but your logout screen is picking up that value first. That's normal. Program that screen to respect the possibility of a null user.
Solution 2:[2]
The reason why it wasn't working is because I was conditional rendering the stacks inside another stack, so I had to change it to
const Navigation = () => {
const { user } = useContext(AuthContext);
return user ? (
<Stack.Navigator>
<Stack.Group>
<Stack.Screen
name="Main"
component={Auth}
options={{
headerShown: false,
}}
/>
<Stack.Screen
name="Users"
component={Users}
options={{headerShown:false}}
/>
</Stack.Group>
</Stack.Navigator>) :
<NonAuth/> }
);
};
export default Navigation;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | windowsill |
| Solution 2 | Tony |
