Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my firebase onAuthStateChanged() trigger multiple times? (React Native)

My firebase method onAuthStateChanged() trigger several times when I sign in and out using firebase-authentication according to console.log. Isn't it supposed to trigger only once at login and once at logout. The result is that when signing out, the navigation to a previous page is triggered several times. Here's the code:

componentDidMount() {
    fbAuth.onAuthStateChanged(user => this.loginFunc(user));
}

loginFunc(user) {
   if (user) {
     console.log('LOGGED IN');
}else {
  console.log('LOGGED OUT');
  this.props.navigation.navigate('FbLogin');
}
console.log('onAUTH LOGGED IN: ', user);
}

This is what the console looks like. As you can see both login and logout are triggered on just a single logout click. On login, it triggers twice....

LOGGED OUT
FbLogin.js:46 onAUTH:  null
LoggedIn.js:27 LOGGED OUT
LoggedIn.js:30 onAUTH LOGGED IN:  null
FbLogin.js:44 LOGGED OUT
FbLogin.js:46 onAUTH:  null

My logout button looks like this:

<TouchableHighlight //LOGOUT
   style={{
      ...
   }}
   onPress={() => {
      fbAuth.signOut();
      this.setState({ loginState: "You are logged out" });
   }}
   >
      <Text>Logout</Text>
   </TouchableHighlight>
like image 262
johanjohansson Avatar asked Apr 17 '18 08:04

johanjohansson


People also ask

How many times will firebase SDK for onAuthStateChanged subscription callback?

Yet, the onAuthStateChanged(...) method is called twice (or three times sometimes).

What does onAuthStateChanged do?

The module provides a method called onAuthStateChanged which allows you to subscribe to the users current authentication state, and receive an event whenever that state changes.


1 Answers

Yes this is normal, onAuthStateChanged will keep triggering, I solved this by using this code:

  var authFlag = true;
  Firebase.onAuthStateChanged( user => {
    if(authFlag) {
      authFlag = false;
      if (user) {
        // Do something,
      }
      else {
        // Alert.alert("Auth Error")
      }
    }
  });
like image 191
Abdulaziz Noor Avatar answered Sep 23 '22 16:09

Abdulaziz Noor