...
/GraphQL Pagination with Apollo Client in React
GraphQL Pagination with Apollo Client in React
In this lesson, we will use GraphQL API to implement the pagination feature for our application.
We'll cover the following...
Finally, you are going to implement another advanced feature while using GraphQL API called pagination.
In this lesson, we will implement a button that allows successive pages of repositories to be queried and a simple “More” button rendered below the list of repositories in the RepositoryList
component. When the button is clicked, another page of repositories is fetched and merged with the previous list as one state into Apollo Client’s cache.
First, let’s extend the query next for your Profile
component with the necessary information to allow pagination for the list of repositories:
const GET_REPOSITORIES_OF_CURRENT_USER = gql`query($cursor: String) {viewer {repositories(first: 5orderBy: { direction: DESC, field: STARGAZERS }after: $cursor) {edges {node {...repository}}pageInfo {endCursorhasNextPage}}}}${REPOSITORY_FRAGMENT}`;
The endCursor
can be used as $cursor
variable when fetching the next page of repositories, but the hasNextPage
can disable the functionality (e.g. not showing the “More” button) to fetch another page. The initial request to fetch the first page of repositories will have a $cursor
variable of undefined
, though. GitHub’s GraphQL API will handle this case gracefully and return the first items from the list of repositories without considering the after
argument. Every other request to fetch more items from the list will send a defined after
argument with the cursor, which is the endCursor
from the query.
Now we have all the information to fetch more pages of repositories from GitHub’s GraphQL API. The Query
component exposes a function to retrieve them in its child function. Since the button to fetch more repositories fits best in the RepositoryList
component, you can pass this function as a prop to it.
const Profile = () => (<Query query={GET_REPOSITORIES_OF_CURRENT_USER}>{({ data, loading, error, fetchMore }) => {...return (<RepositoryListrepositories={viewer.repositories}fetchMore={fetchMore}/>);}}</Query>);
Next, we will use the function in the RepositoryList
component, and add a button to fetch successive pages of repositories that appears when ...