As using a Firestore query, can I get a specific page?
I can get the next page from the current page.
like this.
const loadNext = (documentSnapshots: { docs: string | any[]; }) => {
const lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
const next = query(collection(db, "articleList"),
orderBy('published_at', 'desc'),
where('tags', 'array-contains', 'korean'),
startAfter(lastVisible),
limit(itemsPerPage));
return next
}
I thought if I put the number in startAfter then I could get specific data but it didn't work.
for example If
Total count of data : 200
item per page : 5
want to show : 3rd page
then I put startAfter(10 - 1)
Is it possible to get a specific page from Firestore query?
For example if the total count of data is 200 and the items per page are 5, if I want to show the 3rd page, then I put
startAfter(10 - 1).
That's not how pagination in Firestore works. You cannot know the number of pages ahead of time. If you need that then you'll have to read all the documents beforehand, and this sounds a little costly.
Firestore does not support index or offset-based pagination. As the official documentation regarding loading the data in small chunks mentions, pagination requires that you provide a DocumentReference that represents the starting point for the next query. This means that your pagination will start at the beginning of the query, and then you can load other results using the last document you see on the page (screen).
You can indeed COUNT() the number of documents in the collection and divide it by the number of documents per page, so you can get the number of pages, but why would you do that? I don't see any reason why would you implement such a pagination, since nowadays we are using that so-called infinite scroll. This can be implemented very easily using query cursors and it will cost far less compared to the traditional (SQL) method of paginating the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With