简体   繁体   中英

Is there a way to make firestore real time listener persistent on client-side or server-side?

I'm new to firebase. The goal is i want to only read all data in collection once and keep fetching new updates without refetching all data again when refreshing or closing the web app.

Is it possible? Probably not.

db.collection("cities").where("state", "==", "CA")
.onSnapshot(function(snapshot) {
    snapshot.docChanges().forEach(function(change) {
        if (change.type === "added") {
            console.log("New city: ", change.doc.data());
        }
        if (change.type === "modified") {
            console.log("Modified city: ", change.doc.data());
        }
        if (change.type === "removed") {
            console.log("Removed city: ", change.doc.data());
        }
    });
});

There is no way to make a listener continue to work after the app or process that performs the query has been terminated.

Consider instead adding a timestamp field to each document, and use that to filter for new documents past the last known timestampped document previously read.

You can use snapshot.docChanges() to listen for changes. Like you have.

To maybe help, here is an example I did for a real-time chat app. It's similar to your code. I put it inside the created hook.

With this, I was able to load all data from a firestore doc and listen for newly added messages without having to reload the page. When I added a new message it would appear without having to reload the page.

created() {

    let ref = firestore.collection('< collection here >')
              .doc('< doc ID HERE >')
              .collection('< A Sub collection if you have one >')
              .orderBy('createdAt')

    ref.onSnapshot(snapshot => {

      snapshot.docChanges().forEach(change => {

        if(change.type == 'added') {
          let doc = change.doc

          this.messages.push({
            id: doc.id,
            name: doc.data().name,
            content: doc.data().content,
            timestamp: moment(doc.data().createdAt).format('lll'),
          })
        }
      });

    })
  },

In my data section, I had an empty array. When the page loads everything in the doc is stored in the array, and when the doc changes, the change is pushed onto the array. You can use this array with a v-for in your template and it will update when the doc changes.

messages: [],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM