Offset-based pagination
Offset-based pagination, often associated with navigation via pages, can be achieved through the use of the offset
and limit
options available when querying for data.
Using the following type definition:
type User {
name: String!
}
You would fetch the first "page" of 10 by executing:
query {
users(options: {
limit: 10
}) {
name
}
}
And then on subsequent calls, introduce the offset
argument and increment it by 10 on each call.
Page 2:
query {
users(options: {
offset: 10
limit: 10
}) {
name
}
}
Page 3:
query {
users(options: {
offset: 20
limit: 10
}) {
name
}
}
And so on, so forth.
Total number of pages
You can fetch the total number of records for a certain type using its count query, and then divide that number by your entries per page in order to calculate the total number of pages. This will allow to to determine what the last page is, and whether there is a next page.
See Count queries for details on how to execute these queries.
Paginating relationship fields
Say that in addition to the User
type above, there is also a Post
type which a User
has many of. You can also fetch a User
and then paginate through their posts:
query {
users(where: {
name: "Billy"
}) {
name
posts(options: {
offset: 20
limit: 10
}) {
content
}
}
}
Was this page helpful?