Add Pagination Support

Sorting Order

Before we start, let's do an experiment:

  • Visit a blog post that has more than three comments.
  • Login if you are not logged in
  • Reload the page
  • Add a comment
Q: Were you able to see the comment?

Currently, our pagination system is sorted by the createdAt time of the comment. And it's sorted in the ascending order. Since it only shows three comments at the load time, you won't see your newly added comment.

Here are some ways to fix this issue:

Change the sorting order

You can change the sorting order to the descending. It will fix this issue. For that you just need to replace the getCacheKey function with this:

const getCacheKey = (pageIndex, prevPageData) => {
    // This is first page
    if (pageIndex === 0) {
        return `/api/comments?slug=${slug}&limit=${pageLimit}&sort=-1`

    // This is at the end of the list. We have no more data to fetch
    if (prevPageData.length < pageLimit) {
        console.log('End of the list')
        return null

    // Fetch the next page using createdAt time of the lastComment as the offset
    const lastComment = prevPageData[prevPageData.length - 1]
    return `/api/comments?slug=${slug}&limit=${pageLimit}&offset=${lastComment.createdAt}&sort=-1`

As you can see, the only change is the introduction of the sort=-1 query param.

Show the newly added comment temporarily

Sometimes, we cannot change the order of the list. In that case, we can show the recently added comment. But it's only available for the current browser session. When the user reloads the page, it's gone.

Notify the user of the behavior

This solution goes with the previous one. Instead of temporarily showing the comment, we can display a message to the user about the behavior.

Hide some of the comments in the middle

You can hide comments in the middle & show only a few comments at the top & bottom. This is not something supported by SWR out of the box. But we can implement this by using two useSWRInfinite hooks to fetch top & the bottom of the list.

Then, when we add a new comment, we can call mutate related to the bottom list. Then the user can see the newly added comment right away.

šŸ‘‹ We will look at the above & some advanced pagination topics in a later lesson.

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: