Search code examples
angularfirebaseionic-frameworkgoogle-cloud-firestoreangularfire

Firestore first()).toPromise() always gives old value even I have re-run with new changes


I have this method on a service:

     getUserLink(uid: string): Promise<ConnectionLinkModel> {
            return this.afs.doc<ConnectionLinkModel>
(`userConnectionLinks/${uid}`).valueChanges().pipe(first()).toPromise();
        }

This is working fine for the first time. But let's say I have changed the Firestore data manually and re-run this method again (This is very important. I know since this is promise it'll not listen to the changes automatically. But why it doesn't give new value even though I have re-run it again.). But it never gives changed value. i.e. it always gives old value. How can I handle this use case?

    ngOnInit(): void {
        const res: ConnectionLinkModel = await 
this.connectionLinkService.getUserLink(this.authService.currentUserUid);
      }

Note: When Page loads it runs again. But it'll never give new value. Why?


Solution

  • If you have enabled persistence then the first data you'll get will always be from the local cache.

    From the docs:

    To check whether you're receiving data from the server or the cache, use the fromCache property on the SnapshotMetadata in your snapshot event. If fromCache is true, the data came from the cache and might be stale or incomplete. If fromCache is false, the data is complete and current with the latest updates on the server.

     getUserLink(uid: string): Promise<ConnectionLinkModel> {
    
                    return this.afs.doc<ConnectionLinkModel>(`userConnectionLinks/${uid}`)
                                     .valueChanges()
                                     .pipe(debounceTime(1000)).pipe(first()).toPromise();
                }