I am using firebase authentication for user authentication and react-navigation to render different navigators based on user state. In Firebase.js I listen for auth state change and set state accordingly. The problem is, when I set user data and hide splash screen (npm package react-native-splash-screen) Auth stack can still be seen before Main stack is rendered. I want to ask a question, how could this be solved?
Firebase.js context provider
class Firebase extends React.Component {
constructor(props: Props) {
super(props);
this.state = {
user: null,
userDoc: null,
isLoading: true,
};
}
usersRef = firestore().collection('Users');
componentDidMount() {
const { isLoading, user } = this.state;
auth().onAuthStateChanged(res => {
if (res) {
this.usersRef?.doc(res.uid).onSnapshot(async snapshot => {
this.setState(
{
user: res,
userDoc: snapshot.exists ? snapshot.data() : null,
isLoading:false
},
() => SplashScreen.hide();
);
});
} else {
this.setState(
{
user: null,
isUserSubscribed: false,
isLoading: false,
},
() => SplashScreen.hide();
);
}
});
}
}
RootNavigator.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import MainNavigatorWrapper from '../MainNavigator';
import AuthNavigator from '../AuthNavigator';
import { useFirebase } from '../../context';
const Stack = createNativeStackNavigator();
const RootNavigator = () => {
const { user } = useFirebase();
return (
<NavigationContainer>
<Stack.Navigator}>
{!user ? (
<Stack.Screen name="Auth" component={AuthNavigator} />
) : (
<Stack.Screen name="Main" component={MainNavigatorWrapper} />
)}
</Stack.Navigator>
</NavigationContainer>
);
};