Reuse Query Fields with GraphQL Fragments

Eve Porcello
InstructorEve Porcello
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

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.

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.

egghead
egghead
~ 30 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today