0
0
GraphQLquery~5 mins

Pagination with first and after in GraphQL

Choose your learning style9 modes available
Introduction

Pagination helps you get a small part of a big list at a time. This makes loading data faster and easier to handle.

When showing a list of products on a website page by page.
When loading messages in a chat app little by little.
When displaying search results in chunks instead of all at once.
When you want to save data and speed by not loading everything.
When users scroll and you want to load more items after the current ones.
Syntax
GraphQL
query {
  items(first: Int, after: String) {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}

first tells how many items to get.

after is a cursor that tells where to start after.

Examples
Get the first 5 items from the list.
GraphQL
query {
  items(first: 5) {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}
Get 3 items after the item with cursor "YXJyYXljb25uZWN0aW9uOjQ=".
GraphQL
query {
  items(first: 3, after: "YXJyYXljb25uZWN0aW9uOjQ=") {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}
Sample Program

This query asks for the first 2 items from the list. It also gets the cursor of the last item and if there are more items after.

GraphQL
query {
  items(first: 2) {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}
OutputSuccess
Important Notes

The cursor is a unique string that marks a position in the list.

Use after with the endCursor from the last query to get the next page.

Always check hasNextPage to know if more items exist.

Summary

Pagination with first and after helps load data in small parts.

first sets how many items to get, after sets where to start.

Use cursor and pageInfo to navigate pages smoothly.