Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase onAuthStateChanged is being called twice upon login

I am new to firebase. I'm trying to login using React + Redux. When I click 'Login', it will log me in once, then the onAuthStateChanged is called again with res being null which logs me back out

Here's my Firebase service:

const initFirebase = () => {

    firebase.initializeApp(config.firebase)

    firebase.auth().onAuthStateChanged((res) => {
        console.log('Firebase - onAuthStateChanged', {res})

        if(res) {
            const formData = {
                email: res.email,
                uid: res.uid,
            }

            // Check if email exists against local API
            APIAuthService(endpoint, 'post', formData).then(response => {
                if(response.status) {
                    let userData = response.data
                    store.dispatch(authAction.login(userData))
                }
            })
        }
        else {
            store.dispatch(authAction.logout())
        }
    })
}

Also my Login.js component can viewed here (Line:41) https://pastebin.com/qcRH6gv2

like image 884
Ben Avatar asked Oct 22 '25 18:10

Ben


1 Answers

If someone is looking for a way to simply listen to the state changed only once then just assign the onAuthStateChanged to a variable, that will be the unsubscribed function and simply call it. So for example something like this:

const unsubscribe = onAuthStateChanged(auth, (user) => {
  unsubscribe();
  // Do something with the user...
  console.log('firebase user:', user);
});
like image 172
TheE Avatar answered Oct 24 '25 07:10

TheE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!