How do I properly use onAuthStateChanged from firebase in react native?

对着背影说爱祢 提交于 2020-01-25 09:23:04

问题


I'm a bit confused over the firebase function onAuthStateChanged().

componentDidMount() {
fbAuth.onAuthStateChanged(function(user) {
  if (user) { //THIS TRIGGERS BOTH AT LOGIN AND REGISTRATION
    console.log("LOGGED IN");
  } else {
    //TRIGGERS WHEN LOGGING OUT; NOT WHEN FAILING TO LOGIN!
    console.log("LOGGED OUT");
  }
});
}

I thought that the if(user) block triggered when the user has logged in, but the console.log is also triggered when a new account is created. How do I make a conditional that only triggers at login (and not by creating a new account?)


回答1:


onAuthStateChanged(nextOrObserver, error, completed) returns function()

returns a listener function

Therefore you need to listen it when the component is mounted and unlisten when the component is unmounted

You need to make a separate Component if you want to listen specifically for Login

Login.js // Or whatever your login component is

componentDidMount() {
    // Bind the variable to the instance of the class.
    this.authFirebaseListener = firebase.auth().onAuthStateChanged((user) => {
      this.setState({
        loading: false,  // For the loader maybe
        user, // User Details
        isAuth: true
      });
    });

  }

componentWillUnmount() {
   this.authFirebaseListener && this.authFirebaseListener() // Unlisten it by calling it as a function
}


来源:https://stackoverflow.com/questions/49811230/how-do-i-properly-use-onauthstatechanged-from-firebase-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!