firebase.auth().signOut() not redirecting back to mainNav after clicking logout

Viewed 176

I am building a simple react native app using react native and firebase and facing a small issue when try to log out a user, currently when logout is pressed, it does not redirect back to login page.

home

<Text>Home Screen</Text>
            <Button title="Sign Out" onPress={signOut} />

Signout function

    const signOut = async () => {
        firebase.auth().signOut();
    }

mainNav

const MainNav : FC = () => {
    const [user, setUser] = useState<firebase.User | null>(null);

    const bootstrap = () => {
        firebase.auth().onAuthStateChanged(_user => {
            if(_user){
                setUser(_user)
            }
        })
    }

    

    useEffect(() => {
        bootstrap()
    }, [])


    return (
        <NavigationContainer>
            {user !== null ? <AppStack /> : <AuthStack />}
        </NavigationContainer>
    )
}

export default MainNav;

authstack

import React, { FC } from 'react';
import {createStackNavigator} from '@react-navigation/stack'
import {SignUp, Login} from '../screens'
const {Navigator, Screen} = createStackNavigator();

const AuthStack : FC = () => {
    return (
        <Navigator screenOptions={{headerShown: false}}>
            <Screen name="signup" component={SignUp}/>
            <Screen name="login" component={Login}/>
        </Navigator>
    )
} 

export default AuthStack;

appstack

const AppStack : FC = () => {
    return (
        <Navigator screenOptions={{headerShown: false}}>
            <Screen name="home" component={Home}/>
            <Screen name="dashboard" component={Dashboard}/>
        </Navigator>
    )
} 

export default AppStack;
1 Answers

That's because you are effectively ignoring the logout event:

const bootstrap = () => {
  firebase.auth().onAuthStateChanged(_user => {
    if(_user) { // <-- this will be null when logged out!
      setUser(_user)
    }
  })
}

In addition, you shouldn't be wrapping the onAuthStateChanged function and ignoring its return value (it's unsubscribe function) like you are here:

useEffect(() => {
  bootstrap()
}, [])

You should be using (or a variant of it):

useEffect(() => firebase.auth().onAuthStateChanged(_user => setUser(_user)), [])

The above line keeps user updated with the latest value from firebase.auth() and properly unsubscribes the listener when the component is unmounted.

Related