Challenges

Add Pagination Support

Implement Pagination

Now it's time to implement the pagination logic.

First, replace getCacheKey function with the following:

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

    // This is at the end of the list.
    if (prevPageData.length < pageLimit) {
        return null
    }

    // Here we fetch pages using a offset
    const lastComment = prevPageData[prevPageData.length - 1]
    return `/api/comments?slug=${slug}&limit=${pageLimit}&offset=${lastComment.createdAt}`
}

As you can see, here we return a different "cache key" based on various states of the pagination.

  • When starting, we send the API path to fetch the initial set of data
  • If prevPageData contains less than the size of pageLimit, we can mark this is as the end of the list. So, we will return null to notify that.
  • In other pages, we need to fetch data using an offset. We use the createdAt timestamp of the last comment at that time as the offset.

Then we need to get size & setSize from useSWRInfinite like this:

const {data, mutate, size, setSize} = useSWRInfinite(
    getCacheKey,
    swrFetcher
);

Then introduce the Load More link by adding the following code into the div with the className "comments":

<a
    href="#"
    className="load-more"
    onClick={(e) => {
        e.preventDefault()
        setSize(size + 1)
    }}
>
    Load More
</a>

(Here's the final version of the file after all these changes.)

Now you can click the "Load More" link to fetch more comments.


So, here's a task for you.

  • Make sure you have plenty of comments in your blog post
  • Then click "Load More" until you reach the end
Q: Select the wrong answer?
authenticating...

šŸ™ We need your help

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