Home > Back-end >  Firebase Persisting Auth with Stack Navigator
Firebase Persisting Auth with Stack Navigator

Time:03-24

Attempting to let Firebase persist authentication within the app.js of React Native by doing the following:

There is a sign in page that envokes auth() sign in via Firebase, which works fine, and redirects to the home page via navigation.replace("Home"); however, once the app is closed and relaunched on the emulator, it redirects back to sign in.

This is seemingly what the App.js looks like, I assume that the AuthStateChanged would be prevalent as depicted below, however, user is not accessed in App.js as it is established in SignIn.js, when the Firebase credentials are sent, but I assume it would be similar to this layout?

const App = () => {

  var initialRoute = null

  React.useEffect(() => {
        const unsubscribe = auth().onAuthStateChanged(user => {
            if(user) {
                initialRoute = "Home"
            }
            else {
              initialRoute = "SignIn"
            }
        })

        return unsubscribe
    }, []);

  return (
    <NavigationContainer>
      <Stack.Navigator
        screenOptions={{
          headerShown: false,
        }}
        initialRouteName={initialRoute}
      >

The reason it needs to affect the initial route, and not just redirect anyone who reopens to the home page, is because after registration, there are extra steps included that adjust the database, such as location mapping and etc., therefore, the redirection has to occur within the initial route.

Thanks for your assistance.

CodePudding user response:

This is not how you build a navigation flow with react-navigation. But that's no problem since theres a guide here on the official react-navigation side on how to do that: https://reactnavigation.org/docs/auth-flow/

CodePudding user response:

Fixed by setting two different returns within App.js, one for if the user is authenticated with Firebase that sets the initialRoute to "Home", and one for else that sets it to "SignUp", seems to work fine.

  • Related