eddev

GraphQL Fragments

Share GraphQL selections and generated fragment types across queries.

GraphQL fragments are reusable selections. Use them when the same object shape appears in multiple view, block, or runtime queries.

Fragments live in queries/fragments/**/*.graphql.

fragment ResponsiveImage on MediaItem {
  mediaItemUrl
  caption
  srcSet
  altText
  mediaDetails {
    width
    height
  }
}

Then spread the fragment anywhere the schema returns that type:

query Single($postId: ID!) {
  post(id: $postId, idType: DATABASE_ID) {
    title
    featuredImage {
      node {
        ...ResponsiveImage
      }
    }
  }
}

eddev automatically includes fragment files during codegen, so the fragment type is available in the generated /types.graphql.ts file.

Fragment Types

Import generated fragment types from @generated-types. This is a project alias for the generated /types.graphql.ts file.

import { ResponsiveImageFragment } from "@generated-types"

type Props = Partial<ResponsiveImageFragment>

Tiles And Repeated Shapes

Fragments are especially useful for cards, tiles, and reusable listing components.

fragment CaseStudyTile on CaseStudy {
  uri
  title
  subtitle
  info {
    heroImage {
      ...ResponsiveImage
    }
    categories {
      name
      slug
      uri
    }
  }
}

Then an archive view can select a list of tiles without repeating the fields:

query ArchiveCaseStudies {
  caseStudies(first: 100) {
    nodes {
      ...CaseStudyTile
    }
  }
}

The matching component can use the generated fragment type as its prop shape:

import { CaseStudyTileFragment } from "@generated-types"
import { Link } from "eddev/routing"

type Props = {
  caseStudy: CaseStudyTileFragment
}

export function CaseStudyTile(props: Props) {
  const { caseStudy } = props

  return (
    <article>
      <h2>
        <Link href={caseStudy.uri!}>{caseStudy.title}</Link>
      </h2>
      {caseStudy.subtitle && <p>{caseStudy.subtitle}</p>}
    </article>
  )
}

Prefer one fragment per reusable display shape, not one fragment per database table. A CaseStudyTile fragment is more useful than a generic fragment that tries to include every case-study field.

On this page