Firebase stop listening onAuthStateChanged

后端 未结 2 573
遇见更好的自我
遇见更好的自我 2020-12-02 19:56

As of version ^3.0.0, I\'m having a difficult time removing the auth state change listener.

To start the listener per the documentation:

firebase.a         


        
相关标签:
2条回答
  • 2020-12-02 20:14

    According to the documentation, the onAuthStateChanged() function returns

    The unsubscribe function for the observer.

    So you can just:

    var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
        // handle it
    });
    

    And then:

    unsubscribe();
    
    0 讨论(0)
  • 2020-12-02 20:27

    This has already been answered really well by Frank van Puffelen, but here is my use case for React components that are getting user data. These components need to unsubscribe when the component is unmounted or there will be a memory leak for each of these components.

    React.useEffect(() => {
      let unsubscribe;
      const getUser = async () => {
        unsubscribe = await firebase.checkUserAuth(user => setUser(user));
      };
      getUser();
      return function cleanup() {
        unsubscribe();
      };
    }, []);
    
    0 讨论(0)
提交回复
热议问题