简体   繁体   中英

How do I get Realtime document updates from Firebase Firestore with change.type =="added'

I presently can realtime update modified data with the following code. What I am trying to accomplish is to listen for new documents added and then realtime update my posts. I believe it is in line 8 // listen for new docs that is causing the issues.

getPosts() {
  this.posts = [];

  let loading = this.loadingCtrl.create({
    content: "Loading Feed..."
  });

  loading.present();

  let query = firebase.firestore().collection("posts").orderBy("created", "desc").limit(this.pageSize);

  query.onSnapshot((snapshot) => {
    let changedDocs = snapshot.docChanges();

    changedDocs.forEach((change) => {

      if (change.type == "added") {
        console.log("New Message: ", change.doc.data());
        for (let i = 0; i < this.posts.length; i++) {
          // if (this.posts[i].id === change.doc.id) {
          if (change.doc.isEqual(this.posts[i])) {
            this.posts[i] = change.doc;
          }
        }
      }


      if (change.type == "modified") {
        console.log("Modified Message: ", change.doc.data());
        for (let i = 0; i < this.posts.length; i++) {
          if (this.posts[i].id == change.doc.id) {
            this.posts[i] = change.doc;
          }
        }
      }

    })
  })

query.get()
  .then((docs) => {

    docs.forEach((doc) => {
      this.posts.push(doc);
    })

    loading.dismiss();

    this.cursor = this.posts[this.posts.length - 1];

    console.log(this.posts);

  }).catch((err) => {
    console.log(err)
  })
}

It looks to me like the problem is that you're checking to see if this.posts[i] equals the added doc, and by definition, your doc won't be included in this.posts , since it's a new document. There's nothing in the code that's updated this.posts with the new data yet.

That said, based on your code, I'm not sure I would even bother looking at docChanges. The point of using docChanges is when you want to do something very specific when a doc changes, like adding a fade-out animation when a document is removed from your data or something. Can you simply blow away your old posts array and set the new array equal to the documents you get back in your snapshot listener?

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