Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        console.log('should be an array of user data: ' + response + ', ' + JSON.stringify(response)); //should be an array of user data: undefined, undefined
        for(ud in response){
            await AsyncStorage.setItem('' + ud, '' + response[ud]);
            dispatch({type: 'user_data', payload: response});
        }
    } catch(e){
        dispatch({type: 'add_error', payload: '' + e});
    }
    return dispatch;
    }
};

and

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

I am awaiting for the response and I can see that doc.data() has value. Why can I not see the returned response in getAllUserData()? I hope this is a stupid oversight with the async calls...

doc.data() updates per comments request

Document data: Object {
  "account": Object {
    "email": "[email protected]",
    "password": "password142",
    "phone": "9999999999",
  },
  "id": "test1298347589",
  "info": Object {
    "test123": Array [],
    "test345": "",
    "fullName": "Test 142",
    "interests": Array ["test"],
  },
  "matches": Object {
    "queue": Object {
      "id": "",
    },
  },
  "preferences": Object {
    "ageRange": Array [],
    "distance": 47,
    "lookingFor": Array ["test",],
    "prefData": "test"
  },
}
like image 884
Olivia Avatar asked Sep 20 '25 12:09

Olivia


1 Answers

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 object
          return 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 object
            return doc.data();
        } else {
            console.log("No such document!");
        }
    } catch (error) {
        console.log("Error getting document:", error);
    };
like image 105
Michelle Tilley Avatar answered Sep 23 '25 05:09

Michelle Tilley