Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Reuse Query Fields with GraphQL Fragments


    A GraphQL fragment encapsulates a collection of fields that can be included in queries. In this video, we'll look at how to create fragments on types to reduce the amount of typing that needs to occur as queries become more complex. We'll use the GitHub API to test.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: We'll start with a query for a repository, which takes owner and name as arguments, and then we'll query URL, watchers, and total count. When we click play, we'll get the data about the GraphQL repo, and all of the fields in the response match the field in the query.

    If we take a look at the documentation under the repository query, we'll see that this returns a repository type. Clicking on the repository type will show us what the type is, and what fields can be queried on it.

    Now, using this repository type, we can create a GraphQL fragment. I'll create the fragment called repoFields on repository, and then I'll cut and paste those fields from the query into the repoFields fragment.

    Then we'll use spread syntax to add these fields from the fragment to the query. Let's add to our query to get some data about an organization. We'll pass the login argument, and we'll query email, URL, and repository.

    Repository has an argument passed for name. Now, since repository returns details about the repository type, here I can reuse my fragment. Then if I add any additional fields to this fragment, those will be sent with the query.