Working with Fragments
1. Defining Named Fragments
| Element | Syntax |
|---|---|
| Definition | fragment Name on Type { fields } |
| Spread | ...Name |
| Type condition | Required, must match where spread |
Example: Named fragment
fragment UserCard on User {
id
name
avatar { url }
}
{
me { ...UserCard }
search(q: "x") { ... on User { ...UserCard } }
}
2. Using Fragment Spreads
| Form | Detail |
|---|---|
| Spread | ...FragmentName |
| Validity | Fragment type must overlap with parent type |
| Cycle | Forbidden — fragments cannot recurse |
3. Creating Inline Fragments
Example: Inline fragment
{
hero {
name
... on Droid { primaryFunction }
... on Human { homePlanet }
}
}
| Use | Detail |
|---|---|
| Type narrowing | Select fields specific to a concrete type |
| Directive scoping | ... @include(if: $b) { ... } |
4. Reusing Fragments
| Strategy | Benefit |
|---|---|
| Co-locate fragments with components | UI tree drives data needs |
| Compose fragments | Parent spreads child fragment |
| Codegen | Generates typed accessors per fragment |
5. Using Type Conditions
| Parent Type | Allowed Conditions |
|---|---|
| Object | Same type only |
| Interface | Self or any implementer |
| Union | Any member type |
6. Nesting Fragments
Example: Composed fragments
fragment Avatar on User { avatar { url } }
fragment UserCard on User { id name ...Avatar }
fragment PostCard on Post { id title author { ...UserCard } }
7. Using Fragment Variables
| Aspect | Detail |
|---|---|
| Status | EXPERIMENTAL (Relay-style) |
| Syntax | fragment F on T @argumentDefinitions(n: { type: "Int!" }) |
| Use | ...F @arguments(n: 5) |
8. Organizing Fragment Libraries
| Pattern | Detail |
|---|---|
| Per component | UserCard.fragment.graphql |
| Shared library | fragments/userFields.graphql |
| Codegen near-files | UserCard.tsx + UserCard.generated.ts |
9. Using Interface Fragments
Example: Interface fragment
fragment NodeId on Node { id __typename }
{
node(id: "x") {
...NodeId
... on User { email }
... on Post { title }
}
}