Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Firebase doc.data is undefined

I am trying to get a data from my firebase collection. When I console. the doc.data().name it is returning the name but when I am trying to assign the doc.data().name to a variable it is showing me an error of undefined. I am using Vuex and firebase.

created() {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        console.log(user.uid);
        firebase.firestore().collection("profiles").doc(user.uid)
          .get()
          .then(function(doc) {
            console.log("Document data:", doc.data().name);  // Getting value from firebase
            this.profile.name = doc.data().name;   // Getting Undefined Here
          })
          .catch(function(error) {
            console.log("Error getting document:", error);
          });
      } else {

      }
    });
  }


data() {
    return {
        profile: {
            name: null
        }
    };
  },
like image 915
RAHUL KUNDU Avatar asked Sep 15 '26 20:09

RAHUL KUNDU


1 Answers

Change this:

          .then(function(doc) {
            console.log("Document data:", doc.data().name);  // Getting value from firebase
            this.profile.name = doc.data().name;   // Getting Undefined Here
          })

Into this:

          .then((doc) => {
            console.log("Document data:", doc.data().name);  // Getting value from firebase
            this.profile.name = doc.data().name;   // Getting Undefined Here
          })

Use arrow function, from the docs:

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope

like image 134
Peter Haddad Avatar answered Sep 17 '26 11:09

Peter Haddad