Skip to content Skip to sidebar Skip to footer

Returning Data From Firebase Firestore Async

I have two methods: //authContext.js const getAllUserData = (dispatch) => { return async (userId)=>{ try{ const response = await config.grabUserData(userId)

Solution 1:

grabUserData is incorrect; you forgot to return the promise chain. (Change the final await to return):

//config.js 
grabUserData = async (userId) => {
    var db = firebase.firestore();
    var userId = firebase.auth().currentUser.uid;
    var docRef = db.collection("Users").doc(userId);
    return docRef.get().then(function(doc) {
      if (doc.exists) {
          console.log(doc.data()); //see below for doc objectreturn doc.data();
      } else {
          console.log("No such document!");
      }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });

Since you're using async/await, a more natural way to write this might be:

//config.js 
grabUserData = async (userId) => {
    var db = firebase.firestore();
    var userId = firebase.auth().currentUser.uid;
    var docRef = db.collection("Users").doc(userId);
    try {
        var doc = await docRef.get()
        if (doc.exists) {
            console.log(doc.data()); //see below for doc objectreturn doc.data();
        } else {
            console.log("No such document!");
        }
    } catch (error) {
        console.log("Error getting document:", error);
    };

Post a Comment for "Returning Data From Firebase Firestore Async"