问题
I am trying to build a next.js server-side rendered blog. For it, I need to paginate the posts data. However, I am yet to find a way to use the query cursors firebase provides to paginate the data. The building query code is:
let postsQuery = firebase.firestore().collection('/posts').orderBy('postedOn', 'asc').limitToLast(10);
if (currentTagFilter !== 'All') {
postsQuery = postsQuery.where('tag', '==', currentTagFilter);
}
Now, this works for the first page, but I do not know how to request the next 10 posts. I could have saved the first document of the query and use .endBefore(firstPost). But, if I create some state in _app.js and save the first document in an array, for example, I cannot find how to make it accessible in getServerSideProps. Not to mention, if the user goes straight to /page/2, nothing will be displayed to him as the query for page 1 has not been performed yet.
How can I paginate the data correctly?
回答1:
You might want to rethink you pagination strategy entirely. Firestore doesn't support pagination by index or page number. You have to provide a document snapshot or document details from the last seen document in order to get the next page.
Given these limitations and requirements, it's not possible for the user to go straight to page 2 (or any page other than the first one). So, it would be a bad idea to provide a link or mechanism to do that.
If you want to paginate data "correctly" with Firestore, you have to start at the first page, and cycle through the results using startAfter()
, providing the details of the document where the last page ended. This is illustrated in the documentation.
来源:https://stackoverflow.com/questions/64077225/how-to-paginate-data-in-firebase-in-next-js-ssr-app