SyntaxStudy
Sign Up
GraphQL Fragments and Inline Fragments
GraphQL Beginner 1 min read

Fragments and Inline Fragments

Fragments are reusable field selections that can be spread into multiple queries. They reduce repetition and make it easy to keep the fields fetched for a component co-located with the component itself—a pattern popularized by Relay. Inline fragments are used when a field returns an abstract type (union or interface). The ...on TypeName syntax lets you request type-specific fields and is also how the __typename meta-field is typically used to perform client-side type discrimination.
Example
# ----- Named Fragment -----
fragment ProductFields on Product {
  id
  name
  price
  category { name }
}

query ListProducts {
  featured: products(featured: true) {
    ...ProductFields
  }
  sale: products(onSale: true) {
    ...ProductFields
    discountPercent
  }
}

# ----- Inline Fragments on Union -----
query Search($term: String!) {
  search(term: $term) {
    __typename          # returns "Product", "User", etc.
    ... on Product {
      name
      price
    }
    ... on User {
      email
      role
    }
    ... on Category {
      name
      productCount
    }
  }
}

# ----- Inline Fragment on Interface -----
query GetNodes($ids: [ID!]!) {
  nodes(ids: $ids) {
    id                   # from Node interface
    ... on User  { email }
    ... on Post  { title }
    ... on Order { total }
  }
}