w3resource

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)
  }
}

It's important to note that the component after the "on" clause is designated for the type we are selecting from. In this case, people is of type Person and we want to select the firstName and lastName fields from people(id: "7").

There are two principal uses for fragments in Apollo:

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

Reusing fragments

The most straightforward use of fragments is to reuse parts of queries (or mutations or subscriptions) in various parts of your application.

Colocating 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.

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.

Previous: Pagination
Next: Error handling



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/apollo-graphql/using-fragments.php