Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paginate to previous page using AngularFire, Firestore and Firebase

Sorry I have seen this question has been asked many times in different ways here such as:

  • Howto paginate back to previous pages in a Angular(6) and firebase Firestore setup
  • How to paginate Firestore dataset by individual page?

But NONE of the answers really explain the solution or are understandable.

Also I went though many tutorials such as:

  • https://howtofirebase.com/firebase-data-structures-pagination-96c16ffdb5ca
  • https://rexrainbow.github.io/phaser3-rex-notes/docs/site/firebase-firestore/#paginate

To details:

So here is what I have done so far

let query = ref.orderBy(orderBy, asc ? 'asc' : 'desc').limit(limit);
        if (startAfter) {
          // Thiis works as it should
          query = query.startAfter(startAfter);
        }
        if (endBefore) {
          // This here does not work or give the correct results. I get the first page. 
          query = query.endBefore(endBefore);
        }
        return query;

So:

query = query.startAfter(startAfter); works as expected.

However:

query = query.endBefore(endBefore) does not end before that document I think it ends up to the limit.

like image 632
Jimmy Kane Avatar asked Jan 07 '19 12:01

Jimmy Kane


People also ask

What is pagination in firebase?

Pagination is the process of dividing data into discrete pages. In Firestore, it is achieved by ordering a collection by a field, limiting it to a consistent page size, then offsetting the query. The Firebase Web SDK v7. 3.0 introduced a new limitToLast(n) method that makes the process much easier.

How do I get most recent documents on firestore?

Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!

How do I aggregate data in firestore?

If you want to gain insight into properties of the collection as a whole, you will need aggregation over a collection. Cloud Firestore does not support native aggregation queries. However, you can use client-side transactions or Cloud Functions to easily maintain aggregate information about your data.


1 Answers

As of [email protected] you can use the Query.limitToLast(n: number) method - makes it much easier to move backward with paginated data.

Your implementation details might look something like this:

function nextPage(last) {
   return ref.orderBy('age').startAfter(last.age).limit(3);
}

function prevPage(first) {
   return ref.orderBy('age').endBefore(first.age).limitToLast(3);
}
like image 187
JeffD23 Avatar answered Sep 30 '22 17:09

JeffD23