Sometimes when we're building an app with GraphQL, we start realizing we're requesting the same set of fields over and over again. In a small app like ours with only two data types this isn't a big deal, but imagine if we had dozens of data types with dozens of fields. What if one of those fields changed? We'd have to hunt through our app and fix every single reference to it. What a pain!

This is where GraphQL fragments come into play. Fragments are reusable bits of GraphQL and solve this problem for us. In this video, let's write our first fragment for the fields on the habit data type.

In App.js, we'll write the following:

export const HABIT_FIELDS = gql`
  fragment HabitFields on Habit {
    id
    description
    points
  }
`;

Notice that we're using the keyword fragment, giving it the name HabitFields, and specifying that this fragment is used on Habit.

Then, to use the fragment, we'll modify the habits query like this:

export const HABITS_QUERY = gql`
  query HABITS_QUERY {
    habits {
      ...HabitFields
    }

    totalPoints {
      points
      totalCompletedEntries
    }
  }
  ${HABIT_FIELDS}
`;

Apollo expects us to add that reference to the HABIT_FIELDS variable which contains our fragment below the query but still inside of the tagged template literal.

If you run the client and inspect the the server call, you'll see where Apollo brought in the fragment and sent it to the server.

 

I finished! On to the next chapter