This video is available to students only

Adding pagination

In this lesson, we'll add pagination to both the hook and UI.

Why do we need pagination?#

In this lesson, we're going to add pagination. Why are we doing this? Very often, we don't always want to fetch all the comments. If there are many of them, the API call can be slow and worsen the user experience.

For that reason, we will add pagination so that users can decide whether they want to read more comments by going to the next page. We'll first extend the hook and then add a simple UI.

Let's open the useComments.ts file. We'll make a few modifications.

  1. The useComments function will accept a new parameter — an object withlimit and offset fields. The first one stands for how many comments should be fetched, and the second one where we should start. E.g.,offset: 10 means skip the first ten comments. This object will be optional as someone may still want to fetch all comments.

  1. We will modify the GetComments query to take the limit and offset variables as the next step.

  1. We then need to pass those variables in a fetch call.

  1. Whenever offset or limit change, we need to refetch the comments. For example, when a user goes to the next page, the offset changes. Instead of skipping the first ten comments, we might skip the first twenty. Or the number of comments on one page can be configurable. We should listen to those changes in our hook and fetch the comments accordingly. For that, we'll passlimit and offset to the dependency array in useEffect so that thefetchComments function is called whenever those values change.

  1. We're almost there. However, we currently don't have the total count of all comments when using limit and offset configurations. Total count is necessary when we want to display the number of pages for easier pagination, or we want to show the number of all the comments as we did so far. Hence, we're going to extend the GetComments query to fetch aggregated count as well.

Start a new discussion. All notification go to the author.