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.
useCommentsfunction will accept a new parameter — an object with
offsetfields. The first one stands for how many comments should be fetched, and the second one where we should start. E.g.,
offset: 10means skip the first ten comments. This object will be optional as someone may still want to fetch all comments.
We will modify the
GetCommentsquery to take the
offsetvariables as the next step.
We then need to pass those variables in a fetch call.
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 pass
offsetto the dependency array in
useEffectso that the
fetchCommentsfunction is called whenever those values change.
We're almost there. However, we currently don't have the total count of all comments when using
offsetconfigurations. 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
GetCommentsquery to fetch aggregated count as well.