DEV Community

Cover image for GraphQL fragments explained
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

GraphQL fragments explained

Written by Adhithi Ravichandran✏️

What is a GraphQL fragment?

In this post, we are going to learn about what a fragment is in GraphQL. A GraphQL fragment is a reusable part of the query. In GraphQL, you may run into situations where you need to query for the same fields in different queries. If you notice that your query has many repetitive fields in multiple areas, you can consolidate them into a reusable unit called a fragment.

A GraphQL fragment lets you build multiple fields, and include them in multiple queries. You can think of it as functions in programming languages, that are reusable units.

A GraphQL Fragment is a reusable unit of a GraphQL query, which creates a shared piece of query logic.

The components of a GraphQL fragment

Let’s take a look at the different parts of a GraphQL fragment with a sample structure below:

fragment Name on TypeName {
  field1
  field2
  field3
}
Enter fullscreen mode Exit fullscreen mode

A fragment consists of three unique components:

  • Name : This is the unique name of the fragment (each fragment can have its own name)
  • TypeName : The type of object the fragment is going to be used on. This indicates which nested object, from the GraphQL schema, this fragment is created on
  • Body : The last part is the body of the fragment. The body of the fragment defines the fields that will be queried for

Benefits of using a GraphQL fragment

So why are fragments cool within a GrapQL query?

  • Reusability – With fragments, you can organize your queries into reusable units
  • CachingGraphQL clients make use of fragments, to provide caching options

LogRocket Free Trial Banner

Creating GraphQL fragments

Let’s learn how to create GraphQL fragments with some examples. For the examples in this blog post, I am using GitHub’s public API and writing queries against it. You can follow along by signing into your GitHub account, and executing the queries from the GitHub GraphQL Explorer.

Notice that we are querying for the same fields inside the owner field multiple times. This is a good place to create a fragment:

{
  googleRepo: repository (owner:"google", name:"WebFundamentals") {
    name
    owner {
      id,
      avatarUrl
      resourcePath
      url
    }
  }
  facebookRepo: repository (owner:"facebook", name:"react") {
    name
    owner {
      id,
      avatarUrl
      resourcePath
      url
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

We can rewrite our query to use a fragment. Fragments are created with the keyword fragment.

We can create a fragment called ownerInfo. While creating fragments we have to let GraphQL know on which field it is created. In our case, we are creating the fragment on the RepositoryOwner field. Within our fragment definition, we can include all the fields that we are querying for on the RepositoryOwner object. We are adding id, avatarUrl, resourcePath and url as fields to our fragment.

// fragment ownerInfo for RepositoryOwner fields
fragment ownerInfo on RepositoryOwner {
  id
  avatarUrl
  resourcePath
  url
}
Enter fullscreen mode Exit fullscreen mode

Using a GraphQL fragment

You can then use the fragment that we created in the previous example, within the query by using the … operator and providing the fragment’s name as shown below:

// GraphQL Query with fragments

{
  googleRepo: repository(owner: "google", name: "WebFundamentals") {
    name
    owner {
      ...ownerInfo //fragment
    }
  }
  facebookRepo: repository(owner: "facebook", name: "react") {
    name
    owner {
     ...ownerInfo //fragment
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The snippet shown below is the JSON response after using a fragment. Notice, that there won’t be any changes to the response returned with the use of fragments. Fragments simply make your query clean, readable and reusable. It has no effect on the query response that comes back.

// GraphQL JSON Response

{
  "data": {
    "googleRepo": {
      "name": "WebFundamentals",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjEzNDIwMDQ=",
        "avatarUrl": "https://avatars1.githubusercontent.com/u/1342004?v=4",
        "resourcePath": "/google",
        "url": "https://github.com/google"
      }
    },
    "facebookRepo": {
      "name": "react",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjY5NjMx",
        "avatarUrl": "https://avatars3.githubusercontent.com/u/69631?v=4",
        "resourcePath": "/facebook",
        "url": "https://github.com/facebook"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

I hope you enjoyed writing some GraphQL queries. If you are interested in further learning about GraphQL and getting a big picture overview of GraphQL, you can check out my course GraphQL: The Big Picture on Pluralsight.

Resources:

https://graphql.org/

https://graphql.org/learn/

https://www.graphql.com/

If you have any comments, please post your comments below and share this post with your team and friends.


Editor's note: Seeing something wrong with this post? You can find the correct version here.

Plug: LogRocket, a DVR for web apps

 
LogRocket Dashboard Free Trial Banner
 
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
Try it for free.


The post GraphQL fragments explained appeared first on LogRocket Blog.

Top comments (0)