Pagination With GraphQL
Learn how to implement pagination API with Apollo Server.
We'll cover the following
We’ve already implemented a few queries that fetch multiple products from our backend. However, in all the previous cases, these queries returned all the objects available on the backend. This isn’t very practical!
As soon as our application gets any traction, it’ll collect thousands of products in its database. Fetching and returning thousands of objects on every request is hardly scalable, so if we plan to make our application usable, we need to update our API to return results in a piecemeal fashion.
This is called pagination and in this lesson, we’ll explore how to implement it on both the backend and the frontend of our application. We’ll implement a new query that allows us to get products from the server chunk by chunk. Then, we’ll update the frontend to use the new query instead of the allProducts
query that we’re using now.
We’ll split these steps into three lessons. First, we’ll see how we can implement pagination on the backend. Then, in the next lesson, we’ll implement pagination API on the frontend. And in the third and final lesson, we’ll learn how pagination interacts with Apollo Client’s cache.
Pagination on the backend
Implementing pagination on the GraphQL backend is relatively straightforward. First, we need to implement a new pagination query for fetching products from the backend. There are a few options for designing this API, but we’ll start with the simplest approach so that we can focus on how pagination interacts with various GraphQL features. We’ll discuss the drawbacks of this approach, as well as more sophisticated pagination methods, later in the course.
GraphQL query
To implement pagination, we define a new query called products
. It returns a list of products from our API, sorted by their publication time, and on every request, it returns a part of all available products.
Get hands-on with 1200+ tech skills courses.