the-road-to-react-with-firebase / react-firebase-authentication

🔥 Boilerplate Project for Authentication with Firebase in React.
https://www.robinwieruch.de
1.02k stars 298 forks source link

Add multiple observers to this.listener to React component class #39

Open ThomasJanUta opened 3 years ago

ThomasJanUta commented 3 years ago

Your tutorial really helped me out getting firebase to work nicely in my React app so thanks a lot! 👍

I want to add multiple listeners to a React component. With Firebase authentication, I want to trigger these actions

Form the tutorial:

export class AuthContextProvider extends React.Component {

  componentDidMount() {
    if (!this.state.firebase) {

      /** set listener whether user is signed in */
      this.listener = this.props.firebase.auth().onAuthStateChanged(
        authUser => {
          if (authUser) {
            this.setState({ authUser });
          } else {
            this.setState({ authUser: null });
          }
        },
      );

      /**
       * ########
       * Question: Can I just add another function to this.listener?
       * Will both listeners trigger the appropriate times?
       * ########
       */
      this.listener = this.props.firebase.auth().onIdTokenChanged(
        authUser => {
          if (authUser) {
            // do something
          }
        },
      );
    }
  }
}

It seemed to work in my implementation. Both events are triggered. But it seems wrong to me since I am reassigning this.listener when using .onIdTokenChanged().

How can I add both onAuthStateChanged AND onIdTokenChanged to this.listener correctly?

My question is also about this.listener. What exactly does it do? Where can I find documentation about it? Typing '"this.listener" react' shows many results about window.addEventListener. Is this an equivalent and achieves the same goal?

I assume this in this.listener refers to my class which extends React.Component. The React documentation does not mention anything about the listener property. Please correct me here if this refers to something else.