Cezar
Cezar

Reputation: 23

Firestore onSnapshot 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

Upvotes: 2

Views: 7770

Answers (2)

Mr.Ayanlar
Mr.Ayanlar

Reputation: 449

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());
        });      
    });

Upvotes: 2

user6935527
user6935527

Reputation:

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.com/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.com/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.net/katowulf/cw7dgs8a/

Upvotes: 4

Related Questions