I want to paginate my forum posts stored in Firebase by pages of 20 items, like so:
- User accesses foo.com/1 --> most recent 20 posts are loaded
- User accesses foo.com/2 --> posts 21-40 are loaded
and so on.
Now I am aware I can work with query cursors (as mentioned here), which works perfectly fine for e.g. infinite scroll, because there I start with page 1->2->3 and so on, and each time I have the last visible document available to reference to in my .startAfter(lastVisible)
method.
But what if I want users to be able to access e.g. page 13 to see posts 241-260 directly? Is there a way to start at page document 241, without doing (multiple) queries first to get the lastVisible documents?
Addition:
This is probably very bad, so be carful in implementing the below. I found following way to "solve" this issue:
const pageNo = 1 /* variable */
const postsPerPage = 20
const baseRef = fireDb.collection("posts")
let currentPageRef
if (pageNo === 1) {
currentPageRef = baseRef.limit(postsPerPage)
} else {
let lastVisibleRef = baseRef.limit((pageNo-1) * postsPerPage)
const lastVisibleQuerySnapshot = await lastVisibleRef.get()
const lastVisiblePost = lastVisibleQuerySnapshot.docs[lastVisibleQuerySnapshot.docs.length-1]
currentPageRef = baseRef.startAfter(lastVisiblePost).limit(postsPerPage)
}
const currentPageQuerySnapshot = await currentPageRef.get()
That needs two queries. But it achieves what I want to achieve. Can anyone judge how bad that solution is efficiency/billing? E.g. if someone would access page 999 I fear that will be costly?