1
votes

I am using firestore for an ecommerce project I am working on.

My question is how would I query page 2 directly if the user lands on it.

I have 48 products on every page now I basically need the documents nummer 49 to 97.

How?

I get the whole pagination thing https://firebase.google.com/docs/firestore/query-data/query-cursors

with startAfter and all, but how do you do it, if the person directly lands on Page 2 and I want documents 49 to 97 in the current sorting. Putting a number on the doc is not an option, cause what if he lands with second parameter color=red & page=2 on the side. Also I can not use startAfter cause I dont know the document before number 49.

is that even possible with firestore?

1

1 Answers

0
votes

Since Firestore SDK doesn't have ability to start query from certain page, the only way you can do it is by:

  1. Looping through all pages, and get the next by start after the last of each page.
  2. You get all the data you need, sort it, and get the desired documents.

Sample code for solution no. 1:

//Taken from Firebase code example in the link
Query page = db.collection("cities")
    .orderBy("population")
    .limit(25);

List<DocumentSnapshot> desiredList;

//Looping through each pages, start from the first one
for (int page = 1; page <= desiredPage; page++) {
    page.get()
       .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot documentSnapshots) {
            desiredList = documentSnapshots.getDocuments();

            //This will be ignored if already the last page
            DocumentSnapshot lastPage = desiredList
                  .get(documentSnapshots.size() -1);
            page = db.collection("cities")
                     .orderBy("population")
                     .startAfter(lastPage)
                     .limit(25);
        }
     });
} 

Sample for solution no. 2:

//Taken from Firebase code example in the link
Query allPages = db.collection("cities")
    .orderBy("population")
    .limit(25 * desiredPage);

//Looping through each pages, start from the first one
allPages.get()
     .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot documentSnapshots) {
            //Retrieve only documents from no. something to something
            List<DocumentSnapshot> desiredDocuments = documentSnapshots
                 .getDocuments().subList(25 * (desiredPage - 1), desiredPage * 25);
        }
     });

(Maybe there'll be feature such as, or startAtPage() something like that) While I prefer solution no. 2 for its simplicity, but each developer has it's own preferences.