Skip to content

Pagination

Often, you will have some views in your application where you need to display a list that contains too much data to be either fetched or displayed at once. Pagination is the most common solution to this problem, and Apollo Client has built-in functionality that makes it quite easy to do.

There are basically two ways of fetching paginated data: numbered pages, and cursors. There are also two ways for displaying paginated data: discrete pages, and infinite scrolling. For a more in-depth explanation of the difference and when you might want to use one vs. the other, we recommend that you read Apollo blog post on the subject: Understanding Pagination.

In this article, we'll cover the technical details of using Apollo to implement both approaches.

Using fetchMore

In Apollo, the easiest way to do pagination is with a function called fetchMore, which is returned by the useQuery composition function. This basically allows you to do a new GraphQL query and merge the result into the original result.

js
const { fetchMore } = useQuery(...)

You can specify what query and variables to use for the new query, and how to merge the new query result with the existing data on the client. How exactly you do that will determine what kind of pagination you are implementing.

Offset-based

Offset-based pagination — also called numbered pages — is a very common pattern, found on many websites, because it is usually the easiest to implement on the backend. In SQL for example, numbered pages can easily be generated by using OFFSET and LIMIT.

Let's take this example query loading a feed of potentially infinite number of posts:

vue
<script>
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'

const FEED_QUERY = gql`
  query getFeed ($type: FeedType!, $offset: Int, $limit: Int) {
    currentUser {
      login
    }
    feed (type: $type, offset: $offset, limit: $limit) {
      id
      # ...
    }
  }
`

export default {
  props: ['type'],

  setup (props) {
    const { result } = useQuery(FEED_QUERY, () => ({
      type: props.type,
    }))

    return {
      result,
    }
  },
}
</script>

We can use the fetchMore function returned by useQuery to load more posts in the feed:

js
export default {
  props: ['type'],

  setup (props) {
    const { result, fetchMore } = useQuery(FEED_QUERY, () => ({
      type: props.type,
      offset: 0,
      limit: 10,
    }))

    function loadMore () {
      fetchMore({
        variables: {
          offset: result.feed.length,
        },
      })
    }

    return {
      result,
      loadMore,
    }
  },
}

By default, fetchMore will use the original query, so we just pass in new variables.

Once the new data is returned from the server, the updateQuery option is used to merge it with the existing data, which will cause a re-render of your UI component with an expanded list:

js
export default {
  props: ['type'],

  setup (props) {
    const { result, fetchMore } = useQuery(FEED_QUERY, () => ({
      type: props.type,
      offset: 0,
      limit: 10,
    }))

    function loadMore () {
      fetchMore({
        variables: {
          offset: result.feed.length,
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          // No new feed posts
          if (!fetchMoreResult) return previousResult

          // Concat previous feed with new feed posts
          return {
            ...previousResult,
            feed: [
              ...previousResult.feed,
              ...fetchMoreResult.feed,
            ],
          }
        },
      })
    }

    return {
      result,
      loadMore,
    }
  },
}

The above approach works great for limit/offset pagination. One downside of pagination with numbered pages or offsets is that an item can be skipped or returned twice when items are inserted into or removed from the list at the same time. That can be avoided with cursor-based pagination.

Note that in order for the UI component to receive an updated loading ref after fetchMore is called, you must set notifyOnNetworkStatusChange to true in your useQuery options.

Cursor-based

In cursor-based pagination, a "cursor" is used to keep track of where in the data set the next items should be fetched from. Sometimes the cursor can be quite simple and just refer to the ID of the last object fetched, but in some cases — for example lists sorted according to some criteria — the cursor needs to encode the sorting criteria in addition to the ID of the last object fetched.

Implementing cursor-based pagination on the client isn't all that different from offset-based pagination, but instead of using an absolute offset, we keep a reference to the last object fetched and information about the sort order used.

In the example below, we use a fetchMore query to continuously load new posts, which will be prepended to the list. The cursor to be used in the fetchMore query is provided in the initial server response, and is updated whenever more data is fetched.

js
const FEED_QUERY = gql`
  query getFeed ($type: FeedType!) {
    currentUser {
      login
    }
    feed (type: $type) {
      cursor
      posts {
        id
        # ...
      }
    }
  }
`

export default {
  props: ['type'],

  setup (props) {
    const { result, fetchMore } = useQuery(FEED_QUERY, () => ({
      type: props.type,
      offset: 0,
      limit: 10,
    }))

    function loadMore () {
      fetchMore({
        // note this is a different query than the one used in `useQuery`
        query: gql`
          query getMoreFeed ($cursor) {
            moreFeed (type: $type, cursor: $cursor) {
              cursor
              posts {
                id
                # ...
              }
            }
          }
        `,
        variables: {
          cursor: result.feed.cursor,
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          return {
            ...previousResult,
            feed: {
              ...previousResult.feed,
              // Update cursor
              cursor: fetchMoreResult.moreFeed.cursor,
              // Concat previous feed with new feed posts
              posts: [
                ...previousResult.feed.posts,
                ...fetchMoreResult.moreFeed.posts,
              ],
            }
          }
        },
      })
    }

    return {
      result,
      loadMore,
    }
  },
}

Relay-style cursor pagination

Relay, another popular GraphQL client, is opinionated about the input and output of paginated queries, so people sometimes build their server's pagination model around Relay's needs. If you have a server that is designed to work with the Relay Cursor Connections spec, you can also call that server from Apollo Client with no problems.

Using Relay-style cursors is very similar to basic cursor-based pagination. The main difference is in the format of the query response which affects where you get the cursor.

Relay provides a pageInfo object on the returned cursor connection which contains the cursor of the first and last items returned as the properties startCursor and endCursor respectively. This object also contains a boolean property hasNextPage which can be used to determine if there are more results available.

The following example specifies a request of 10 items at a time and that results should start after the provided cursor. If null is passed for the cursor relay will ignore it and provide results starting from the beginning of the data set which allows the use of the same query for both initial and subsequent requests.

js
const FEED_QUERY = gql`
  query getFeed ($type: FeedType!, $cursor: String) {
    currentUser {
      login
    }
    feed (type: $type, first: 10, after: $cursor) {
      edges {
        node {
          id
          # ...
        }
      }
      pageInfo {
        endCursor
        hasNextPage
      }
    }
  }
`

export default {
  props: ['type'],

  setup (props) {
    const { result, fetchMore } = useQuery(FEED_QUERY, () => ({
      type: props.type,
    }))

    function loadMore () {
      fetchMore({
        variables: {
          cursor: result.feed.pageInfo.endCursor,
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          const newEdges = fetchMoreResult.feed.edges
          const pageInfo = fetchMoreResult.feed.pageInfo

          return newEdges.length ? {
            ...previousResult,
            feed: {
              ...previousResult.feed,
              // Concat edges
              edges: [
                ...previousResult.feed.edges,
                ...newEdges,
              ],
              // Override with new pageInfo
              pageInfo,
            }
          } : previousResult
        },
      })
    }

    return {
      result,
      loadMore,
    }
  },
}

The @connection directive

When using paginated queries, results from accumulated queries can be hard to find in the store, as the parameters passed to the query are used to determine the default store key but are usually not known outside the piece of code that executes the query. This is problematic for imperative store updates, as there is no stable store key for updates to target. To direct Apollo Client to use a stable store key for paginated queries, you can use the optional @connection directive to specify a store key for parts of your queries. For example, if we wanted to have a stable store key for the feed query earlier, we could adjust our query to use the @connection directive:

graphql
query Feed($type: FeedType!, $offset: Int, $limit: Int) {
  currentUser {
    login
  }
  feed(type: $type, offset: $offset, limit: $limit) @connection(key: "feed", filter: ["type"]) {
    id
    # ...
  }
}

This would result in the accumulated feed in every query or fetchMore being placed in the store under the feed key, which we could later use for imperative store updates. In this example, we also use the @connection directive's optional filter argument, which allows us to include some arguments of the query in the store key. In this case, we want to include the type query argument in the store key, which results in multiple store values that accumulate pages from each type of feed.

Released under the MIT License.