Reputation: 367
i want to return the value from the firestore OnSnapshot function so that i can retrieve the url of user image. I am using vuejs and firestore. And i have activeUserImg
function in created property of vue.
activeUserImg: function () {
const u = firebase.auth().currentUser;
firebase.firestore().collection('Colleges').doc(u.uid).onSnapshot(function(doc) {
var img_arr=[];
this.img_arr.push(doc.data())
this.img= doc.data().logo
});
return this.img || this.$store.state.AppActiveUser.img;
}
and everytime it is the showing the value in return as undefined.
the image code:
<img
v-if="activeUserImg.startsWith('http')"
key="onlineImg"
:src="activeUserImg"
alt="user-img"
width="40" height="40"/>
<img
v-else
key="localImg"
:src="require(`@/assets/images/portrait/small/${activeUserImg}`)"
alt="user-img"
width="40" height="40"/>
Upvotes: 0
Views: 386
Reputation: 411
You can wrap the function in a promise and wait for when the result is available.
Example:
activeUserImg: () => {
return new Promise(function(resolve, reject) {
const u = firebase.auth().currentUser;
firebase
.firestore()
.collection('Colleges')
.doc(u.uid)
.onSnapshot(function(doc) {
var img_arr=[];
this.img_arr.push(doc.data())
this.img= doc.data().logo
// return the result
resolve(this.img || this.$store.state.AppActiveUser.img);
});
});
}
Then, you can access the value by
activeUserImg.then(result => {
console.log(result);
})
Or
const result = await activeUserImg()
console.log(result)
Upvotes: 1
Reputation: 2039
return statement should be inside of the firestore callback just like below
activeUserImg: function () {
const u = firebase.auth().currentUser;
firebase.firestore().collection('Colleges').doc(u.uid).onSnapshot(function(doc) {
var img_arr=[];
this.img_arr.push(doc.data())
this.img= doc.data().logo
return this.img || this.$store.state.AppActiveUser.img;
});
}
Upvotes: 0