Pagination

Pagination

What is Pagination?

Pagination is the technique of dividing a large set of data into smaller, manageable chunks or pages.

Think of it like flipping through pages of a book instead of reading the whole book on one giant scroll.


Why Use Pagination?

  1. Performance: Loading thousands of items at once can slow down apps.
  2. User Experience: Easier to navigate smaller sets of data.
  3. Efficiency: Reduces memory and bandwidth usage.


Real-Life Example: An Online Store

  • Imagine an online store with 1,000 products.
  • Instead of loading all products at once, you show 10 products per page.
  • Users can navigate using "Next" and "Previous" buttons.


How Pagination Works in GraphQL

In GraphQL, pagination is often implemented using two main techniques:


Offset-Based Pagination

  • Uses limit (how many items to fetch) and offset (where to start).
  • Simple but can be inefficient with large datasets.

Example Query: Fetch 5 Users Starting from the 6th User

query {
    users(limit: 5, offset: 5) {
        id
        name
    }
}
        

Expected Response:

{
    "data": {
        "users": [
            { "id": "6", "name": "User6" },
            { "id": "7", "name": "User7" },
            { "id": "8", "name": "User8" },
            { "id": "9", "name": "User9" },
            { "id": "10", "name": "User10" }
        ]
    }
}
        

Cursor-Based Pagination (Recommended for Large Data)

  • Uses cursor instead of offset for better efficiency.
  • Useful when data might change often (additions or deletions).

Example Query: Fetch 3 Users After a Specific Cursor

query {
    users(first: 3, after: "cursor123") {
        edges {
            node {
                id
                name
            }
        }
        pageInfo {
            hasNextPage
            endCursor
        }
    }
}
        

Expected Response:

{
    "data": {
        "users": {
            "edges": [
                { "node": { "id": "4", "name": "User4" } },
                { "node": { "id": "5", "name": "User5" } },
                { "node": { "id": "6", "name": "User6" } }
            ],
            "pageInfo": {
                "hasNextPage": true,
                "endCursor": "cursor456"
            }
        }
    }
}
        

Key Concepts in Cursor-Based Pagination:

  • Edges: The actual data items.
  • Node: A single item inside an edge.
  • PageInfo: Metadata like hasNextPage and endCursor for navigation.


Which One to Use?

  • Offset-Based: Simple lists, small datasets.
  • Cursor-Based: Large datasets, real-time apps.

要查看或添加评论,请登录

Kumar Preeti Lata的更多文章