Klement Tan
Klement Tan

Reputation: 301

Returning value of promise from an observer

I want to write a helper function that returns the firebase user token id. I managed to get the firebase token from this approach but I am having trouble in returning the promise value (token id) from the observer function of onAuthStateChange to the functions that calls the getToken() helper method. I am very new promises and would greatly appreciate any help. Here is what I got so far.

export function getToken (){
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      user.getIdToken().then(token => {
        return token // Managed to get the valid token
      })
    } else {
    }
  });
}

Upvotes: 2

Views: 298

Answers (3)

technophyle
technophyle

Reputation: 9149

First of all, onAuthStateChanged() is an event listener as you mentioned, so subscribing to it each time the getToken() method is called is not a good idea.

I don't believe it's possible to create one "magic" function to achieve what you want.

I understand that you're looking for a way to "wait" for the firebase token to have a value, but no, it's not possible because if user's state is logged out, the event will not be triggered until they log in, so a promise doesn't make sense. If such a promise existed, it would be unresolved forever if the user just doesn't feel like logging in.

That's why instead of a promise, we have the event listener. As the other answerer said, the best way is to act on the actual event. For example, you can broadcast a message throughout your application, set a global state, etc. which in turn can be listened and used in relevant components.

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317712

Firebase Auth state listeners/observers can't return a value from a function. They get invoked for each change in state. If you want to continue some work when the state changes, you should do that in the listener itself, possibly by calling another function.

Upvotes: 1

David Innocent
David Innocent

Reputation: 676

An if should self close. If you have returned when the value is true, then you should also return something when it is not in the else statement.

Upvotes: -1

Related Questions