Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  141] [ 1]  / answers: 1 / hits: 5728  / 5 Years ago, sun, december 1, 2019, 12:00:00

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
}
};
},

More From » firebase

 Answers
1

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



[#5466] Wednesday, November 27, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;