Learn Relay/
← 0305 →

04 - usePaginationFragment

Learn how to use usePaginationFragment to paginate a list of posts.

Exercise

  • use usePaginationFragment on Feed.tsx component to fetch a list of posts and later on paginate it
  • implement pagination on loadMore callback (load 10 more posts each time)

Extras

  • hide the Load More button when there are no more posts (hasNext)
  • show a loading indicator while the next page is loading (isLoadingNext)

Code Helpers

  • usePagination fragment
fragment Feed_query on Query {
  posts(first: $first, after: $after) @connection(key: "Feed_posts", filters: []) {
    endCursorOffset
    startCursorOffset
    count
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
    edges {
      node {
        id
        ...Post_post
      }
    }
  }
}
  • @argumentDefinitions: declare "local" arguments to your fragments
@argumentDefinitions(
  first: { type: Int, defaultValue: 10 }
  after: { type: String }
)
  • @refetchable: let Relay generate a refetch query for your pagination or refetch fragments
@refetchable(queryName: "FeedPaginationQuery")
  • loading the next page
const { data, loadNext, hasNext, isLoadingNext } = usePaginationFragment(fragment, props.query);

loadNext(10);
Next: useMutation →
Loading editor…
localhost:7500 · in-browser GraphQL server
Checks verify your solution against the running app.
  • ○Feed uses usePaginationFragment with a @refetchable fragment
  • ○Renders the first page of posts
  • ○Load More fetches the next page with FeedPaginationQuery
  • ○Paginates until all the 30 posts are loaded