How to apply pagination on documents in firebase in descending order

Firebase

If you have an app that retrives data from firebase, then 9 out of 10 times, we have to show the latest data on the top. This helps in maintaining user engagement as every time user opens he will find a new article/post etc as per your app.

I recently made a quote app, where I used to show the quote in the same order of insertion so the latest quote was always getting appended to the last position. I achieved this by using the following firebase query

quotesRef.orderBy("id", Query.Direction.ASCENDING).limit(limit); // for the first time
quoteRef.orderBy("id", Query.Direction.ASCENDING).startAfter(last_quote_id).limit(limit); // for next consecutive request

So when I realized I have to do it in descending order I just updated the query direction from ascending to descending. This lead to a bug because of that my app was getting infinitely scrolled, the quotes were getting repeated again and again. This must be happening because of the id property, I was not sure.

I spent a good amount of time around this, so here it is, how I solved it

The idea is the startAfter function also accepts a query document, so instead of maintaining the id, we will maintain the query document and use it here this made sure the app know the exact position after which it has to continue retrieving.

quotesRef.orderBy("id", Query.Direction.DESCENDING).limit(limit); // for the first time
quoteRef.orderBy("id", Query.Direction.DESCENDING).startAfter(last_quote_document).limit(limit); // for next consecutive request

This code will solve the problem. Voila!!! Problem solved

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *