Jacob Ruiz

View Original

GraphQL Pagination: hasNextPage

Problem

How do we figure out if there is a next page during pagination?

Solution

When querying the database, artificially grab one more item than the client asked for.

This lets us peek into the future. 👀

Then we can ask, “Is the length of the retrieved list longer than the number of items the client actually asked for?”

If yes, it means there’s at least one more item waiting for them on the next page.

If no, it means they’ve reached the end of the list.

We can ask this question like this:

See this content in the original post

posts is the result of a database request where we’ve artificially set the limit to one more than the client asked for.

limit is the actual limit that the client asked for.

We then trim off the extra node before returning the data to the client.

Implementation

See this content in the original post

Sources:

The Road To GraphQL

GraphQL Docs: Pagination

Apollo Docs: Pagination

Apollo Blog: Explaining GraphQL Connections