26
votes

I am reading some data from Firebase's Cloud Firestore but I've seen several ways to do it. The example I saw used the get and onSnapshot function like this:

db.collection("cities").doc("SF")
 .onSnapshot(doc => {
      console.log(doc.data());
 });

or this

var docRef = db.collection("cities").doc("SF");

docRef.get().then(doc => {
    if (doc.exists) {
         console.log("Document data:", doc.data());
    } else {
         console.log("No such document!");
    }
}).catch(function(error) {
   console.log("Error getting document:", error);
        });

Is there any difference between them?

1

1 Answers

37
votes

As explained in the doc:

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries:

  • Call a method to get the data.
  • Set a listener to receive data-change events.

When you set a listener, Cloud Firestore sends your listener an initial snapshot of the data, and then another snapshot each time the document changes.

When you use get() you "retrieve the content of a single document" only once. It's a kind of "get and forget": If the document changes in the (back-end) Firestore database you will need to call get() again to see the change.

On the opposite, if you use the onSnapshot() method you constantly listen to a document as explained in the doc:

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

As explained in these docs, these two methods apply to one document or to a collection of documents (including a query).