How To Use GraphQL Fragments with React

21 Jan · by Tim Kamanin · 3 min read

If you're reading this, probably you know how awesome (or painful) GraphQL is. Since we're all developers here and one of our mantras is DRY (which stands for ... well you know what it means, don't you?) we might cringe a little bit when we see repeating parts in our GraphQL queries.

Consider the following GraphQL query/mutation pair that fetches and updates a product:

export const GET_PRODUCT = gql`
  query getProduct($id: ID!) {
    product(id: $id) {
      id
      title
      description
      image
      price
    }
  }
`;
export const UPDATE_PRODUCT = gql`
  mutation productUpdate($product: ProductInput!) {
    productUpdate(input: $product) {
      product {
        id
        title
        description
        image
        price
      }
    }
  }
`;

I guess we both agree there's a repeating part that begs us to get extracted:

{
  id
  title
  description
  image
  price
}

Fragments to the rescue!

It turns out that GraphQL people are also smart and they had the same awkward feeling. Thus they created a thing that allows us to extract a fragment of a query and re-use it in another query. And they called the thing (drumroll please) Fragments.

Here's how we can define a fragment in JS/React code:

export const PRODUCT_DETAILS_FRAGMENT = gql`
   fragment ProductDetails on Product {
      id
      title
      description
      image
      price
   }
`

Where

  • ProductDetails is the name of the fragment, you can call it whatever you want.
  • on Product is the name of the GraphQL resource and it should match the resource you're trying to query, in our case it's Product.

So now we can simplify our query/mutation pair to:

export const GET_PRODUCT = gql`
  query getProduct($id: ID!) {
    product(id: $id) {
      ...ProductDetails
    }
  }
  ${PRODUCT_DETAILS_FRAGMENT}
`;
export const UPDATE_PRODUCT = gql`
  mutation productUpdate($product: ProductInput!) {
    productUpdate(input: $product) {
      product {
        ...ProductDetails
      }
    }
  }
  ${PRODUCT_DETAILS_FRAGMENT}
`;

Please note how we inject our fragment into query/mutation:

  1. We add a fragment to a place where we'd typically describe a product output:

    product {
       ...ProductDetails
    }
    

    Don't miss the ... in front of the ProductDetails.

  2. We inject ${PRODUCT_DETAILS_FRAGMENT} at the end of the query/mutation, so GraphQL knows where to look for a ProductDetails fragment.

And that's all! Now you know this powerful technique to make your GraphQL codebase more DRY and organized. Enjoy and let me know in the comments below if that helped you.

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials

Comments