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
}
};
},
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With