17

I have a web application(Angular) and mobile application(Ionic). Both of them share the same Firestore data.

Use web application update existing data but the ionic app shows duplicate items(the duplicates will be gone after restart the mobile app), I check the item data itself in Firestore, it was updated and unique. Does anyone have any clue on this?

This issue only occurs on the mobile app other than the web app, both of them use "angularfire2": "^5.0.0-rc.4",

   import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';

   this.posts$ = this.db.getRecentPosts().snapshotChanges().pipe(
      map(arr => arr.map(doc => {
          return { id: doc.payload.doc.id, ...doc.payload.doc.data() }
        }
      ))
    );

Did research and it seems like(not 100% sure) an angularfire2 issue: AngularFirestoreCollection sometimes returns duplicate of records after inserting a new record

enter image description here

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125

1 Answers1

6

Since duplicates are gone after restart and other people report this issue as well it feels to me that the problem is within AngularFirestore itself. As a workaround you could try the following:

 import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';

   this.posts$ = this.db.getRecentPosts().snapshotChanges().pipe(
      map(arr => arr.reduce((acc, doc) => { // map -> reduce
        const id = doc.payload.doc.id
        // remove !(id in acc) to get last duplicate
        !(id in acc) && acc[id] = { id, ...doc.payload.doc.data() } 
        return acc }
        }, {} // reduce seed
      )),
      // you can also Object.values(arr.reduce(...)), but this I find bit more readable
      map(coll => Object.values(coll))
    );
artur grzesiak
  • 20,230
  • 5
  • 46
  • 56
  • 1
    Thanks for your reply. Currently, I remove duplicates by myself. I really want to know what's the best solution for avoiding the issue. – Haifeng Zhang Oct 09 '18 at 18:31
  • Have you figured this out?? Every time I update something, it duplicates on the front end. This seems like something which has been dealt with some other way no? – l3o Sep 02 '20 at 21:19