Challenges

Add Pagination Support

Introducing useSWRInfinite

First open components/Comments.js, and apply following changes:

To use SWR with offset based pagination, we need to use a different hook. So, let's import it:

import { useSWRInfinite } from 'swr'

Then replace the existing use of useSWR hook with the following:

const getCacheKey = (pageIndex, prevPageData) => {
    return `/api/comments?slug=${slug}`
}

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

With useSWRInfinite, we are using a function to get the cache key. We will discuss more about it soon.

Then replace the let comments = data line with the following:

let comments = null
if (data) {
    comments = []
    for(const pageData of data) {
        comments = [...comments, ...pageData]
    }
}

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

The useSWR hook has a property called data that contains what it returns from the swrFetcher. In our case, it an array of comments.

But with useSWRInfinite, it's a list of such arrays. Or, in other terms, a list of pages.

šŸ’” Here we introduce a new term called Page. Basically, with pagination, we load a set of pages by clicking next or load-more links. Such a page contains a set of data usually coming from a single API call.

In useSWRInfinite, data for a page is coming from the fetcher (specifically, from swrFetcher). That's why data property contains a list of array.


Now, try to run your app with these changes. Then check the comments you created in the previous section.

Q: What's the outcome of the experiment?
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: