Chris
Chris

Reputation: 5814

How do I use Javascript Promise Chaining with Firebase Authentication and Firebase?

I need to utilize a key stored in my firebase using the user's firebase user id.

The steps to my function are the following:

1) Get the Firebase User ID after authentication

2) Using the Firebase User ID, pull the stored API Key value (which I saved in a node: app/{Firebase User Id})

3) Using the stored API Key value, run my last function

After doing some research, I've come to the conclusion that I should use Javascript Promise Chaining to the below code, which I'm having a difficult time doing

firebase.initializeApp({databaseURL: "{}"});
var dbRef = firebase.database();

function pull_api_key_from_firebase_after_auth(func){
  firebase.auth().onAuthStateChanged((user) => {
  if (user) {
     var app_ref = dbRef.ref('app').child(user.uid);
     app_ref.on("child_added", function(snap) {
        dictionary_object = snap.val()
        api_key = dictionary_object.api_key
        func(api_key)
      })
    }
  });
}

function final_function(api_key){
   console.log('processing final function')
}

pull_api_key_from_firebase_after_auth(final_function)

Alternatively, I'd like to make api_key a global variable as such:

function pull_api_key_from_firebase_after_auth(func){
      firebase.auth().onAuthStateChanged((user) => {
      if (user) {
         var app_ref = dbRef.ref('app').child(user.uid);
         app_ref.on("child_added", function(snap) {
            dictionary_object = snap.val()
            api_key = dictionary_object.api_key
            localStorage.setItem('api_key',api_key)

          })
        }
      });
    }

api_key = localStorage.getItem('api_key')
final_function(api_key)

However I cant figure out how to make final_function as well as my other functions wait until api_key is defined

Upvotes: 0

Views: 1349

Answers (1)

Ronnie Smith
Ronnie Smith

Reputation: 18595

You must use firebase.auth().onAuthStateChanged to get the uid bcs .auth.currentUser.uid will NOT be available on page load. It shows up a microsecond after (it's asynchronous).

To do what you want simply build out a promise function and call it within .onAuthStateChanged and .then do your other function. You custom promise might look like:

function fetchUserData(){
    return new Promise(function(resolve, reject){
        var db = firebase.firestore(); // OR realtime db
        db.collection("users").get().then(function(snap) {
            resolve (snap);
        }).catch(function(error) {
            reject (error);
        });
    }); 
}

Within .onAuthStateChange just do something like:

fetchUserData().then((snap) => {
    // do your thing

})
.catch((error) => {
    console.log(error);
});

Upvotes: 2

Related Questions