4

I am trying to build a webpage with AngularFireStore as my data store. In order to enable infinite scrolling, I am trying to query the store with limit and startAfter functionality of AngularFireStore.

For some reason, I am not able to get it working. The limit functionality is not working as expected as it returns values greater / lesser than the actual limit, and there are duplicate values as well

I have searched and tried few approaches (this, this, this). But nothing works.

Here is what I have tried:

crudService.ts :

readNextPost(cursor){
    return this.firestore.collection('MyCollection',
                                      ref => ref.orderBy('date', 'desc')
                                                .startAfter(cursor)
                                                .limit(10)
                                                ).snapshotChanges();
  }

component.ts

mapResponseToObject(data) {
  return {
    id: data.payload.doc.id,
    doc: data.payload.doc
  }
}

setLastPost(data) {
  this.lastFetchedPost = data[data.length - 1].doc;
}

fetchNextPosts() {
    this.crudService.readNextPost(this.lastFetchedPost).subscribe(data =>{
      let nextPost = data.map(this.mapResponseToObject)
      this.allPosts = [...this.allPosts, ...nextPost];
      this.setLastPost(nextPost);
    })
  }

readNextPost returns values less than 10 although there are more than that in the store, and some times returns more than 10, which has values that were fetched earlier. This causes duplicate data visible in the webpage.

As a newbie to both AngularFireStore and Angular 10, I am stuck at this issue for several hours. Any help would be much appreciated. Many thanks.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
veri_pudicha_coder
  • 1,411
  • 9
  • 9

1 Answers1

0

Try the subscribe:

  this.firestore.collection('MyCollection',
                                  ref => ref.orderBy('date', 'desc')
                                            .startAfter(cursor)
                                            .limit(10)
                                            ).get()
                       .subscribe(response => {
                        for (const item of response.docs) {
                            console.log(item.data());
                          }
                    });;

I think snapshotChanges is a stream of "Changes", not the full result of the query.I'm assuming that means changes to the result of the query but the docs aren't too clear:

https://github.com/angular/angularfire/blob/master/docs/firestore/collections.md#snapshotchanges

user1689987
  • 1,002
  • 1
  • 8
  • 23