loading...
Cover image for GraphQL Fragments

GraphQL Fragments

shevchenkonik profile image Nik Shevchenko ・2 min read

Introduction

GraphQL Fragment is a reusable part of the query. Fragments let you construct sets of fields and then include them in different queries of your application. You can think of it as functions in programming languages, that are reusable units of your code. Here's an example of how you could solve the above situation using fragments and support of DRY practice in your queries and components.

Fragment description

# Fragment
fragment name on Type {
  id
  name
}

A fragment consists of parts:

  • Fragment name (name)

This is the custom name of the fragment and every fragment will be with own name

  • Object Type (Type)

This is a type of object where you use a fragment

  • Body of fragment (id, name)

This defines the fields of the shared query

How to use GraphQL Fragments

Let's use the Artsy API, artists and artworks collections:

# Fragment of Artist
fragment artistInfo on Artist {
  id
  name
  bio
}

# Queries
{ 
  trending_artists(name: ARTIST_INQUIRY) {
    artists {
      ...artistInfo
    }
  }

  popular_artists {
    artists {
      ...artistInfo
    }
  }
}

The syntax of using a fragment is similar to the JavaScript spread operator. And the idea of a fragment is the same –– to assign the keys and values of one object to another object. ... give GraphQL command assigns the fields from the custom fragment to the current selection set. In our example we are able to select the name, bio, and id in two different queries using one instance of a fragment, it's cool.

Playground of this example on GraphQL Arty's.

Why do you need to use GraphQL Fragments?

  • Reusable part of queries

You can organize your queries into small units with reusable parts with fragments. This is the best practice for performance and components architecture of your application.

  • Caching

The fragments are also frequently used in frontend caching clients like ApolloClient or Relay. ApolloClient provides methods for interacting with cached data (https://www.apollographql.com/docs/react/caching/cache-interaction/).

In Relay, we have the so-called fragment container, which defines the component’s data requirements of the component.

  • Static typing

We can generate static types from GraphQL for TypeScript or Flow.

Resources

Posted on by:

shevchenkonik profile

Nik Shevchenko

@shevchenkonik

Software, research & development of reality

Discussion

pic
Editor guide