Cursor-Based Pagination
- Cursor-Based Pagination uses a unique marker known as a cursor to navigate through results.
- Each data entry has a unique cursor serving as a bookmark for different entries.
- It allows for proper structuring and relatively faster performance when dealing with large datasets that change dynamically.
- Instead of fetching by page numbers, it fetches data based on the cursor, which points to a specific entry in the dataset.
- Cursors are more efficient for navigating large datasets compared to offset pagination.
Let’s take an Example:
Let’s develop a GraphQL query to retrieve user information in a paginated manner. The query should fetch the first 5 users after a specified cursor. The query should return the user’s id, name, and email. Additionally, the query should provide metadata including the total count of users, a flag indicating if there is a next page, and the end cursor for the current page.
query GetUsers {
users(first: 5, after: "cursor123") {
edges {
cursor
node {
id
name
}
}
totalCount
pageInfo {
hasNextPage
endCursor
}
}
}
Response:
{
"data": {
"users": {
"edges": [
{
"cursor": "cursor1",
"node": {
"id": "1",
"name": "John Doe",
"email": "john.doe@example.com"
}
},
{
"cursor": "cursor2",
"node": {
"id": "2",
"name": "Jane Smith",
"email": "jane.smith@example.com"
}
},
...
],
"totalCount": 100,
"pageInfo": {
"hasNextPage": true,
"endCursor": "cursor50"
}
}
}
}
Explanation: The output includes an array of user objects, each with a cursor and details like id, name, and email. Additionally, metadata like the total user count, and whether there’s a next page and the end cursor is provided.
Pagination in GraphQL
Pagination in GraphQL is a powerful tool that allows developers to efficiently retrieve large amounts of data by breaking it into smaller, more manageable parts. This not only enhances the performance of data queries but also reduces the burden on servers and networks.
In this article, We will learn about Pagination along with its types also see some examples, and so on.