admin管理员组

文章数量:1399905

I have a function that gets data from Firestore, but always return undefined. I had previously used .get() method, but I want my data to be auto-updated when the database gets some new data.

I know that .onSnapshot() doesn't return a promise, so using asynchronous is not an option.

getdata = (dbRef) => {
                dbRef.onSnapshot(snapshot => {
            console.log(snapshot);
            return snapshot;
        });
    }

The log display the snapshot in the console, but when I call that function, it returns undefined

I have a function that gets data from Firestore, but always return undefined. I had previously used .get() method, but I want my data to be auto-updated when the database gets some new data.

I know that .onSnapshot() doesn't return a promise, so using asynchronous is not an option.

getdata = (dbRef) => {
                dbRef.onSnapshot(snapshot => {
            console.log(snapshot);
            return snapshot;
        });
    }

The log display the snapshot in the console, but when I call that function, it returns undefined

Share Improve this question edited May 2, 2019 at 13:40 Frank van Puffelen 601k85 gold badges890 silver badges860 bronze badges asked May 2, 2019 at 10:03 CezarCezar 231 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Your question isn't very clear. If you trying to get real time updates then you use this model from this documentation https://firebase.google./docs/firestore/query-data/listen

db.collection("cities").doc("SF")
.onSnapshot(function(doc) {
    console.log("Current data: ", doc.data());
});

if you trying to get one time data then use this model from this documentation https://firebase.google./docs/firestore/query-data/get-data

docRef.get().then(function(doc) {
if (doc.exists) {
    console.log("Document data:", doc.data());
} else {
    // doc.data() will be undefined in this case
    console.log("No such document!");
}

I think the doc is really clear about this.

And BTW I'm sure that onSnapshot in real time updates is also asynchronous. If you want to get real time updates then you can't have it in function. For function use one time data model. Here is very nice example for real time updates

http://jsfiddle/katowulf/cw7dgs8a/

You can read the tutorial on this link "listen realtime updates"

db.collection("cities")
    .onSnapshot(function(querySnapshot) {
        let cities = [];
        querySnapshot.forEach(function(doc) {
            cities.push(doc.data());
        });      
    });

本文标签: javascriptFirestore onSnapshot returns undefinedStack Overflow