简体   繁体   中英

How does firebase's onAuthStateChanged work in ComponentDidMount lifecycle in reactJS

Can anyone explain we how this onAuthStateChanged function is working inside componentDidMount. I know this lifecycle hook get executed only once when the component is mounted. So how does the function inside gets executed?

What I assume is it's like callback function which keeps on running in event loop as gets fired when state changed like addEventlistner in JS.

componentDidMount() {
    console.log("Context Mounted");
    firebaseapp.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({ currentUser: user });
        console.log("User Signed IN ");
      } else {
        console.log("THERE IS NO USER");
      }
    });
  }

You pretty much got the gist of it: after your register your onAuthStateChanged callback with Firebase it will be called:

  1. "immediately" with the current authentication state
  2. whenever that authentication state changes

Since you call setState to put the user into the state, this then triggers a rerender of the UI whenever one of the above events occurs.

This continues until the app exits or until your unregister the listener, which you should typically do in the componentWillUnmount method of the same component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM