Reputation: 23
I get the following error:
ERROR The 'navigation' object hasn't been initialized yet.
This might happen if you don't have a navigator mounted,
or if the navigator hasn't finished mounting.
See https://reactnavigation.org/docs/navigating-without-navigation-prop#handling-initialization
for more details.
I initially had the following:
const Stack = createNativeStackNavigator();
export default function App() {
const navigation = useNavigation();
...
useEffect(() => {
const subscriber = auth.onAuthStateChanged((_user) => {
if (!_user) {
navigation.navigate('Login');
...
}
else {
navigation.navigate('CoreTabs', { screen: 'Home' })
}
});
return subscriber;
},[]);
I adjusted my code as follows (following instructions in URL provided with error.)
const Stack = createNativeStackNavigator();
export default function App() {
// const navigation = useNavigation(); // removed
const navigationRef = useNavigationContainerRef(); // added
...
useEffect(() => {
const subscriber = auth.onAuthStateChanged((_user) => {
if (!_user) {
// navigation.navigate('Login'); // removed
if (navigationRef.isReady) navigationRef.navigate('Login'); // added
}
else {
...
navigation.navigate('CoreTabs', { screen: 'Home' }) // removed
if (navigationRef.isReady) navigationRef.navigate('CoreTabs', { screen: 'Home' }) // added
}
});
return subscriber;
},[]);
However I continue to receive the error. Here's how my NavigationContainer
is setup.
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Group>
{ user && <Stack.Screen name="CoreTabs" component={CoreTabs} /> }
<Stack.Screen name="Login" component={LoginScreen} }}/>
<Stack.Screen name="Registration" component={RegistrationScreen}/>
<Stack.Screen name="Reset Password" component={ResetPasswordScreen}/>
</Stack.Group>
<Stack.Group screenOptions={{ presentation: 'modal' }}>
<Stack.Screen name="Notifications" component={NotificationsScreen} />
<Stack.Screen name="Edit Profile" component={ProfileEditScreen} />
</Stack.Group>
</Stack.Navigator>
</NavigationContainer>
);
Upvotes: 0
Views: 1616
Reputation: 2761
I don't think you can use the useNavigationContainerRef
hook outside the NavigationContainer.
You can get the navigationContainerRef like this.
const navigationRef = useRef()
return <NavigationContainer ref={navigationRef}>...</NavigationContainer>
Upvotes: 1