Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features
Autoplay

    Reuse Query Fields with GraphQL Fragments

    Eve PorcelloEve Porcello
    graphqlGraphQL

    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.

    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    Instructor: 00:00 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.

    00:16 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.

    00:29 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.

    00:42 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.

    00:57 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.

    Discuss

    Discuss