angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

snapshotChanges trigger twice

Open eliavmaman opened this issue 6 years ago • 19 comments

Version info

Angular:8

AngularFire:"5.2.1

I have main component that retrieve data from collection and i have sub component that retrieve different data from the same collection.

whats happened is that the sub-component snapshotChanges() trigger twice with the data it should retrieve and the data that retrieved by the parent component.

Parent component:

this.firestore.collection('galleries', ref => ref.where('user', '==', this.user.id)
      .orderBy('date', 'desc'))
      .snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as any;
        data.id = a.payload.doc.id;
        return data;
      }))).subscribe((sessions) => {
         console.log(sessions);
      });

Child component:

this.firestore.collection('galleries', ref => ref.limit(6).orderBy('date', 'desc'))
      .snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as any;
        data.id = a.payload.doc.id;
        return data;
      }))).subscribe((sessions) => {console.log(sessions)})

in the child component i've limit the query to 6 document ' but it's subscription called twice, and displays both parent data child documents. Any idea?

eliavmaman avatar Feb 25 '20 22:02 eliavmaman

Any one?

eliavmaman avatar Feb 26 '20 06:02 eliavmaman

I think I am facing the same

jimmykane avatar Feb 26 '20 15:02 jimmykane

Yes it's like super basic and no one complains about it

eliavmaman avatar Feb 26 '20 15:02 eliavmaman

https://github.com/angular/angularfire2/issues/1552

So you might be getting first the cache and then the server results

jimmykane avatar Feb 26 '20 15:02 jimmykane

It's not the same

eliavmaman avatar Feb 26 '20 15:02 eliavmaman

sure you are not subscring through an asyncpipe in the component template?

mosesweb avatar Mar 09 '20 14:03 mosesweb

I am now also facing this issue @jamesdaniels and others

jimmykane avatar Apr 06 '20 19:04 jimmykane

I believe I have the same problem. I have a component (The Problem) that returns the correct results consistently when run but itself, or after any other component except one (The Cause). When it runs after this component, the query will first return the records from The Cause, and then return the correct records.

A pipe/tap to console shows the double batches of records returning on the single query. The results are identical with valueChanges or snapshotChanges. Both components are using the same service, but different queries. The Cause is looping through doc ids and "getting" each to hydrate the entity, where The Problem is a query with orderBy, startAfter, and limit.

I find it interesting that the problem respects "limit". If The Cause has a limit larger than The Problem, the smaller limit will be returned followed briefly by the correct records and limit.

I tried to setup a simple demo, with three components, but it works as it should. I don't see what is different with The Problem and The Cause.

sumpton avatar Apr 18 '20 00:04 sumpton

Hi, I have referenced the issue above.

Use get. It fires 2 times because the first result is from local cache, and the second the online update

On Sat, 18 Apr 2020, 02:10 Jerry Sumpton, [email protected] wrote:

I believe I have the same problem. I have a component (The Problem) that returns the correct results consistently when run but itself, or after any other component except one (The Cause). When it runs after this component, the query will first return the records from The Cause, and then return the correct records.

A pipe/tap to console shows the double batches of records returning on the single query. The results are identical with valueChanges or snapshotChanges. Both components are using the same service, but different queries. The Cause is looping through doc ids and "getting" each to hydrate the entity, where The Problem is a query with orderBy, startAfter, and limit.

I find it interesting that the problem respects "limit". If The Cause has a limit larger than The Problem, the smaller limit will be returned followed briefly by the correct records and limit.

I tried to setup a simple demo, with three components, but it works as it should. I don't see what is different with The Problem and The Cause.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/angular/angularfire/issues/2336#issuecomment-615517943, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAJVX473W57DXFUBZOYTCHDRNDVZFANCNFSM4K3UC35Q .

jimmykane avatar Apr 18 '20 07:04 jimmykane

My solution is kind of hacky but I include auditTime(2000) in the pipe to provide enough time for that second query to come through.

this.collection$(path, query).pipe(auditTime(2000),take(1)).toPromise();

kyleabens avatar Apr 24 '20 16:04 kyleabens

@kyleabens I appreciate you sharing your hack. It works for me. 500ms works in my instance currently.

@jimmykane I don't understand using "get".

sumpton avatar Apr 26 '20 18:04 sumpton

i have the same problem.

this occurs when i do a snapshotChanges() on a collection, while there is already another active snapshotChanges() on the same collection. the late coming subscription first receives the results cached from the former subscription. then after a while it receives the actual results.

i think this is a very problematic design. when i execute a query, it should return me only once, not twice. i shouldn't be trying to handle two different results from one query. this either complicates my code, or makes me disable some features i would like to present to my users.

the cached results should be returned only when firestore servers can not be contacted, that is, the query should return either the correct result or cached result. not both.

ondokuzz avatar May 02 '20 22:05 ondokuzz

I think it would be fine that it returns twice, if there were also a way for me to differentiate where the data came from. Then I could decide for myself when to display cached results.

EdRW avatar May 16 '20 07:05 EdRW

This is answered at https://github.com/firebase/firebase-js-sdk/issues/2976, which is a desired behaviour.

You can filter it by using the snapshot.payload.doc.metadata.fromCache property on the snapshots from snapshotChanges() or any other method call that uses DocumentChangeAction.

KingDarBoja avatar Aug 25 '20 14:08 KingDarBoja

This is my solution using RxJS operator distinctUntilChanged and lodash isEqual function. With it you can avoid twice triggering and get benefits from the cache usage

this.afs.collection(path).doc<any>(id).snapshotChanges()
  .pipe(distinctUntilChanged((prev, curr) => _.isEqual(prev?.payload.data(), curr?.payload.data())))

similar for valueChanges

this.afs.collection(path).doc<any>(id).valueChanges()
  .pipe(distinctUntilChanged((prev, curr) => _.isEqual(prev, curr)))

TomasMasiulis avatar Mar 05 '21 10:03 TomasMasiulis

This might help - https://stackoverflow.com/questions/67514628/angular-firestore-subscribe-fires-twice/67514861#67514861

mauriciogracia avatar Nov 11 '21 15:11 mauriciogracia

This is my solution using RxJS operator distinctUntilChanged and lodash isEqual function. With it you can avoid twice triggering and get benefits from the cache usage

this.afs.collection(path).doc<any>(id).snapshotChanges()
  .pipe(distinctUntilChanged((prev, curr) => _.isEqual(prev?.payload.data(), curr?.payload.data())))

similar for valueChanges

this.afs.collection(path).doc<any>(id).valueChanges()
  .pipe(distinctUntilChanged((prev, curr) => _.isEqual(prev, curr)))

@TomasMasiulis what would be the equivalent while doing snaphotChanges() or valueChanges() on Collection rather than Document? or is it not possible?

EmreAkkoc avatar Sep 16 '22 13:09 EmreAkkoc

This might help - https://stackoverflow.com/questions/67514628/angular-firestore-subscribe-fires-twice/67514861#67514861

This worked well for me.

madmacc avatar Apr 26 '23 22:04 madmacc

TomasMasiulis what would be the equivalent while doing snaphotChanges() or valueChanges() on Collection rather than Document? or is it not possible?

I did this by setting a "lastUpdated" timestamp on the documents I was querying in my collection and extended the distinctUntilChanged(...) operator, like this:

ValueChanges:


this.afs.collection('yourCollectionPath', ref => ref.where(...)).valueChanges().pipe(
    distinctUntilChanged((a, b) => {
        // If the size of the query result has changed, there are changes.
        if (a.length !== b.length) return false;

        // Do your custom compare here.
        // I used the timestamp since my documents often updated only once every 12 hours.
        // Returning `false` will continue the changes to your subscription.
        for (let i = 0; i < a.length; i++) {
            const previous = a[i], current = b[i];
            if (previous.lastUpdated.toDate().getTime() !== current.lastUpdated.toDate().getTime()) { 
                return false;
            }
        }

        // If no changes are detected, return `true` to ignore this emission.
        return true;
    })
)

For SnapshotChanges, this will be very similar, the only difference would be how you access the data - the only adjustment required is how you set the previous and current variables. The same code as above, with only the forloop adjusted for SnapshotChanges:

...
for (let i = 0; i < a.length; i++) {
    const previous = a[i].payload.doc.data(), current = b[i].payload.doc.data();
    if (previous.lastUpdated.toDate().getTime() !== current.lastUpdated.toDate().getTime()) return false;
}
...

I realize that not all scenarios you will be able to set a lastUpdated field and handle it the way I have. However, you are able to implement the same pattern and change how you determine the distinctUntilChanged to evaluate to false to get the same effect.

fouchekeagan avatar Jul 21 '23 09:07 fouchekeagan