Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase stop listening onAuthStateChanged

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.auth().onAuthStateChanged(function (user) {
    // handle it
});

However, I cannot find anywhere in the documentation that refers to a remove auth state change listener. There is peculiar function on the Firebase.Auth class called removeAuthTokenListener. Unfortunately it's not documented (firebase docs reference).

Via your browser's web console.

var auth = firebase.auth();
auth.removeAuthTokenListener;

prints a function definition that takes one parameter. I tried to do the following:

this.authListener = firebase.auth().onAuthStateChanged(function (user) {...});
firebase.auth().removeAuthTokenListener(this.authListener);

but that didn't do anything.

like image 631
James Gilchrist Avatar asked May 22 '16 03:05

James Gilchrist


People also ask

How do I stop onAuthStateChanged?

So you can just: var unsubscribe = firebase. auth().

What is onAuthStateChanged in firebase?

According to the documentation, the onAuthStateChanged() function returns. The unsubscribe function for the observer. So you can just: var unsubscribe = firebase.


2 Answers

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();
like image 97
Frank van Puffelen Avatar answered Oct 11 '22 18:10

Frank van Puffelen


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 unsubscribe;
}, []);
like image 32
theGiantOtter Avatar answered Oct 11 '22 18:10

theGiantOtter