My App is crashing with no error logs on the console when I'm trying to navigate between screens based on the onAuthStateChanged() method.
Navigation Packages used : "@react-navigation/native": "^6.0.6", "@react-navigation/stack": "^6.0.11",
can somebody help me?
Loading.js
import React, { useEffect } from "react";
import firebase from '../config/firebase';
import { View, StyleSheet, ActivityIndicator, StatusBar } from "react-native";
import { CommonActions } from '@react-navigation/native';
export default function Loading({ navigation }) {
StatusBar.setBarStyle('dark-content');
useEffect(() => {
console.log('from useEffect');
firebase.auth().onAuthStateChanged((user)=>{
if(user!=null ){
navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [
{ name: 'HomeRoute' },
],
})
)
// navigation.navigate('HomeRoute')
}else{
navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [
{ name: 'LoginRoute' },
],
})
)
// navigation.navigate('LoginRoute');
}
})
})
return (
<View style={styles.container}>
<ActivityIndicator size='large' color='#333333' style={styles.indicator} ></ActivityIndicator>
</View>
);
}
App.JS
import Login from './screens/Login';
import Home from './screens/Home';
import Loading from './screens/Loading';
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='LoadingRoute' screenOptions={{headerShown: false}}>
<Stack.Screen name='LoginRoute' component={Login} />
<Stack.Screen name='HomeRoute' component={Home} />
<Stack.Screen name='LoadingRoute' component={Loading} />
</Stack.Navigator>
</NavigationContainer>
);
}
You got dispatch action a bit off.
You are passing in an index: 1 which is telling the navigation to focus the route at index 1 once the navigation is finished.
The problem is you have only a single route inside routes, so you should tell the navigation to focus route at index 0 like so
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{ name: "LoginRoute" }],
})
);
I would also highly advise reading the official docs on how to set up your authentication flow with react-navigation.
TLDR: What you should do basically is conditionally render the routes based on the user login state and let react-navigation handle the rest for you.