Fragments
Reuse field selections with named fragments, pick type-specific fields with inline fragments, and see how the validator checks type conditions and cycles.
Fragments
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A named fragment, fragment BookCard on Book { ... }, is a reusable group of fields that you add with a spread: ...BookCard.
- A fragment has a type condition, and the validator only allows spreading it where an object of that type, or a type that overlaps it, can appear.
- Inline fragments, ... on Type { ... }, select fields that exist only on one member of an interface or union, and can also group fields under a directive.
- Fragments are a query-writing convenience: the server merges them, and the response contains no trace of them.
- Component-based clients attach a fragment to each component so that every component declares exactly the data it needs.
Stop retyping the same fields
A comparison page shows two books, each with a title, a year, and the author’s name. With aliases you write:
{
a: book(id: "10") { title year author { name } }
b: book(id: "12") { title year author { name } }
}
Two copies of the same three lines. When design adds price to the card, you edit both. Add a third book, and there are three places. This is the repetition fragments exist to remove.
fragment BookCard on Book {
title
year
author { name }
}
query Compare {
a: book(id: "10") { ...BookCard }
b: book(id: "12") { ...BookCard }
}
fragment BookCard on Book { ... } defines a reusable set of fields. ...BookCard is a spread, and it means “put those fields here”. Running this on graphql-js 17.1.0 returned for a the title The Dispossessed, year 1974 and author Ursula K. Le Guin, and for b Cosmos, 1980, Carl Sagan. The response has a and b and no mention of BookCard. A fragment is a query-writing convenience. The server expands it before running, and what you get back is exactly what you would get from the long version.
The type condition
on Book is the type condition: it says which type this group of fields belongs to. That is what lets the validator check you. Spread a fragment where its type cannot occur and you get an error:
fragment F on Author { name }
{ book(id: "10") { ...F } }
# Fragment "F" cannot be spread here as objects of type "Book" can never be of type "Author".
Other checks, each of which I triggered:
- A fragment that is defined but unused: “Fragment “F” is never used.”
- A spread of a name that does not exist: “Unknown fragment “Nope”.”
- Fragments that spread each other in a loop: “Cannot spread fragment “A” within itself via “B”.”
Fragments may spread other fragments, as long as there is no cycle.
Inline fragments
An inline fragment has no name and is written where it is used:
{
items {
title
... on Book { pages }
... on Album { tracks }
}
}
You used this already in the interfaces and unions lessons. A field that returns an abstract type only guarantees the shared fields. To read fields of a particular member, you write an inline fragment on it. The server applies the fragment only to values of that type.
The type condition is optional for an inline fragment, and then the fragment is just a way to attach something, usually a directive, to a group of fields:
{ book(id: "10") { ... { year } } }
That is valid and returns the year. It becomes useful with @include, shown in directives.
Fragments in real front ends
Written by hand in one query, fragments save typing. Their real value shows in component-based clients such as Apollo Client and Relay. Each component declares its data needs as a fragment, fragment BookCard_book on Book { ... }, and the page query spreads the fragments of every component it renders. This is called colocation: the UI and its data requirements live in one file, and when a component stops needing a field, you delete it from that component’s fragment alone. Apollo Client basics and urql and Relay pick this up.
Conventions and pitfalls
- Name fragments after the type and the component, such as
BookCard_book, so they stay unique across a whole project; fragment names must be unique within a document. - Spreading a fragment into a
@includeor@skipfield is allowed. - Do not use fragments to hide a huge selection. A fragment is clean to read, yet the server still fetches every field in it.
- Fragments spread fields of the same object. They cannot rename, filter, or transform; they only select.
What the video covers
Jamie Barton’s “GraphQL Fragments” is under three minutes, published October 2021. Its description says it works with fragments inside queries and mutations, as well as variables and nested fragments. It is short, and I could not read a transcript, so I cannot describe its examples; the type-condition errors above come from my own runs. Two runners-up are linked: the My Digital Diaries EP04 episode (its chapter list puts fragments at 04:42) and Ben Awad’s two-minute explainer from 2018.
Where this fits
Queries can now be tidy and reusable. The values inside them, such as ids and filters, should not be pasted into the text. Next: variables and operation names.
Check yourself
What are the two forms of fragment and what is each used for?
A named fragment declares a reusable field group spread with ...Name, and an inline fragment ... on Type { } selects fields for one concrete type inside a field of an interface or union.
Why does fragment F on Author { name } fail when spread inside a book selection?
A Book can never be an Author, so the validator says the fragment cannot be spread there.
What happens to a fragment that is defined but never spread?
The validator rejects the document with Fragment is never used, since unused definitions are an error.
Do fragments change what the response looks like?
No. The server expands them while executing, and the response has the same keys as if you had written the fields out by hand.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.