Pagination (Cursors)

In the realm of GraphQL, once you've grasped connections, nodes, and edges, understanding cursors and pageInfo becomes a breeze. This page delves into the mechanics and importance of these components in pagination.

1. Cursors: The Heart of Pagination

Cursor: A unique identifier for a specific record in a dataset. In GraphQL, it's usually an encoded string representing a specific position in a dataset.

Why Use Cursors?

  • Precision: Cursors point to specific positions in a list, allowing for precise data retrieval.

  • Efficiency: Avoids issues like duplicate or skipped records that might occur in real-time data updates with offset-based pagination.

  • Flexibility: Supports seamless integrations like infinite scrolling.

2. PageInfo: The Guide to Navigation

PageInfo: A set of fields providing metadata about the current page of results. It tells you where you are and whether there's more data to fetch.

Typical Fields:

  • hasNextPage: A boolean indicating if there are more items after the current set.

  • hasPreviousPage: A boolean showing if there are items preceding the current set.

  • startCursor: The cursor for the first item in the current set.

  • endCursor: The cursor for the last item in the current set.

3. Using Cursors and PageInfo Together

Combining cursors with pageInfo provides a robust pagination experience. For instance, by using the endCursor from pageInfo and the after argument in a query, you can fetch the next set of records seamlessly.

4. Sample Query with Cursors and PageInfo

{
  units(first: 5, after: "current_cursor_value") {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}

Here,

  • The after argument uses a cursor to determine the starting point for fetching the next 5 properties.

  • pageInfo provides the endCursor, which you can use for subsequent queries.

5. Best Practices

  • Always use cursors as provided; decoding or modifying them manually can lead to unexpected results.

  • Rely on pageInfo for navigation cues, especially to determine if more data fetching is necessary.

Last updated