Catch the highlights of GraphQLConf 2023! Click for recordings. Or check out our recap blog post.
v1
Features
Using Fragments

Using Fragments

A GraphQL fragment is a shared piece of query logic.

fragment NameParts on Person {
  firstName
  lastName
}
 
query getPerson {
  people(id: "7") {
    ...NameParts
    avatar(size: LARGE)
  }
}

There are two principal uses for fragments in Apollo:

  • Sharing fields between multiple queries, mutations or subscriptions.
  • Breaking your queries up to allow you to co-locate field access with the places they are used.

In this document we'll outline patterns to do both; we'll also make use of utilities in the graphql-anywhere and graphql-tag packages which aim to help us, especially with the second problem.

Reusing Fragments

The most straightforward use of fragments is to reuse parts of queries (or mutations or subscriptions) in various parts of your application. For instance, in GitHunt on the comments page, we want to fetch the same fields after posting a comment as we originally query. This way we can be sure that we render consistent comment objects as the data changes.

To do so, we can simply share a fragment describing the fields we need for a comment:

import gql from 'graphql-tag';
 
CommentsPage.fragments = {
  comment: gql`
    fragment CommentsPageComment on Comment {
      id
      postedBy {
        login
        html_url
      }
      createdAt
      content
    }
  `,
};

We put the fragment on CommentsPage.fragments.comment by convention, and use the familiar gql helper to create it.

When it's time to embed the fragment in a query, we simply use the ...Name syntax in our GraphQL, and embed the fragment inside our query GraphQL document:

const SUBMIT_COMMENT_MUTATION = gql`
  mutation submitComment($repoFullName: String!, $commentContent: String!) {
    submitComment(repoFullName: $repoFullName, commentContent: $commentContent) {
      ...CommentsPageComment
    }
  }
  ${CommentsPage.fragments.comment}
`;
 
export const COMMENT_QUERY = gql`
  query Comment($repoName: String!) {
    # ...
    entry(repoFullName: $repoName) {
      # ...
      comments {
        ...CommentsPageComment
      }
      # ...
    }
  }
  ${CommentsPage.fragments.comment}
`;

Collocating Fragments

A key advantage of GraphQL is the tree-like nature of the response data, which in many cases mirrors your rendered component hierarchy. This, combined with GraphQL's support for fragments, allows you to split your queries up in such a way that the various fields fetched by the queries are located right alongside the code that uses the field.

Although this technique doesn't always make sense (for instance it's not always the case that the GraphQL schema is driven by the UI requirements), when it does, it's possible to use some patterns in Apollo client to take full advantage of it.

Imagine this view hierarchy:

FeedPage
└── Feed
    └── FeedEntry
        ├── RepoInfo
        └── VoteButtons

The FeedPage conducts a query to fetch a list of Entrys, and each of the subcomponents requires different subfields of each Entry.

The graphql-anywhere package gives us tools to easily construct a single query that provides all the fields that each subcomponent needs, and allows to easily pass the exact field that a component needs to it.

Creating Fragments

To create the fragments, we again use the gql helper and attach to subfields of ComponentClass.fragments, for example:

VoteButtons.fragments = {
  entry: gql`
    fragment VoteButtons on Entry {
      score
      vote {
        vote_value
      }
    }
  `,
};

If our fragments include sub-fragments then we can pass them into the gql helper:

FeedEntry.fragments = {
  entry: gql`
    fragment FeedEntry on Entry {
      commentCount
      repository {
        full_name
        html_url
        owner {
          avatar_url
        }
      }
      ...VoteButtons
      ...RepoInfo
    }
    ${VoteButtons.fragments.entry}
    ${RepoInfo.fragments.entry}
  `,
};

Filtering With Fragments

We can also use the graphql-anywhere package to filter the exact fields from the entry before passing them to the subcomponent. So when we render a VoteButtons, we can simply do:

import { filter } from 'graphql-anywhere';
 
<VoteButtons
  entry={filter(VoteButtons.fragments.entry, entry)}
  canVote={loggedIn}
  onVote={type =>
    onVote({
      repoFullName: full_name,
      type,
    })
  }
/>;

The filter() function will grab exactly the fields from the entry that the fragment defines.

Importing fragments when using Webpack

When loading .graphql files with graphql-tag/loader, we can include fragments using import statements. For example:

#import "./someFragment.graphql"

Will make the contents of someFragment.graphql available to the current file. See the Webpack Fragments section for additional details.