Compose component data requirements
Several UI components need different parts of one resource in a single request.
GraphQL · Const
GraphQL fragments are reusable field selections that can be spread into queries. Named fragments support composition, while inline fragments select fields for a concrete type returned through an interface or union.
A named fragment packages a reusable set of fields for a particular object, interface, or union type. Place it in a query with the spread syntax (...FragmentName); the server applies its selection fields at that location. Inline fragments provide type-specific fields when a field returns an interface or union.
fragment FragmentName on TypeName {
field
...NestedFragment
}
...FragmentNamequery GetUser {
user(id: "1") {
...UserFields
}
}
fragment UserFields on User {
id
name
email
}The query reuses the named UserFields selection wherever the user fields are needed.
Several UI components need different parts of one resource in a single request.
The same group of fields appears in multiple operations.
A response field may contain multiple concrete object types.
A fragment is a reusable selection set. A named fragment declares its type condition and is inserted with a fragment spread, so repeated field selections can be shared across queries or components.
Follow-up: How do you query a union-specific field? Use an inline fragment with the concrete object type as its type condition, then select that type's fields inside it.
The declaration uses fragment Name on Type, followed by a selection set. The fragment is included with ...Name wherever that selection is needed.
Follow-up: Can a fragment be nested? Yes. A fragment can spread another fragment, allowing larger selections to be composed from smaller reusable selections.
Inline fragments are needed when a field returns an interface or union and the requested field belongs to a concrete implementing object. The type condition makes the concrete type explicit.
Follow-up: What happens when the runtime value is a different member of the union? Fields inside the fragment are returned only when the runtime object matches the fragment's type condition.
inline fragmentsqueriesinterfacesunion typesselection sets