GraphQL Fragment

  • Because GraphQL is declarative data fetching library, we can't ask for all fields, no wildcard like * used in SQL.
  • Use fragment as workaround to "sorta" get all fields
    • fragment is associated with a particular type
  • use fragment to associate with certain UI components (common use case)
  • use fragment to query in compact form
query AllLifts {
allLifts {
...LiftDetails
}
}
fragment LiftDetails on Lift {
id
name
elevationGain
capacity
night
status
trailAccess {
name
status
}
}
  • fragments are not defined in the GraphQL schema, defined in the client
const ALL_PERSONS = gql`
{
allPersons {
...PersonDetails
}
}
fragment PersonDetails on Person {
name
phone
address {
street
city
}
}
`
  • defined once saving to variable for reuse
const PERSON_DETAILS = gql`
fragment PersonDetails on Person {
id
name
phone
address {
street
city
}
}
`
const ALL_PERSONS = gql`
{
allPersons {
...PersonDetails
}
}
${PERSON_DETAILS}
`