HomeToolsAbout

Fragments

What is it

Share fields between operations.

Piece of logic that can be shared between multiple queries and mutations.

  • Used to reuse common pieces of query logic in multiple places within a GraphQL query.

You do not use fragment when the fields are not common in multiple nodes.

fragment NameParts on Person { firstName lastName }

NameParts fragment can be reused with any Person object.

  • Person type must have firstName and lastName fields for this fragment to be valid.

Every fragment includes a subset of the fields that belong to its associated type.

query GetPerson { people(id: "7") { ...NameParts avatar(size: LARGE) } }

... syntax is used to include a fragment in a query much like spread syntax in JS

Equivalent to:

query GetPerson { people(id: "7") { firstName lastName avatar(size: LARGE) } }

Fragments with Arguments

query HeroNameAndFriends($episode: Episode) { hero(episode: $episode) { name friends { name } } } # argument { "episode": "JEDI" }
// returns all JEDI { "data": { "hero": { "name": "R2-D2", "friends": [ { "name": "Luke Skywalker" }, { "name": "Han Solo" }, { "name": "Leia Organa" } ] } } }
AboutContact