Using Fragments

Learn how to use GraphQL fragments with Apollo Client.

So far, we’ve used two different GraphQL queries in our frontend to fetch data about posted products. One problem with these queries is that they’re querying a duplicated list of fields.

This isn’t an issue by itself, but we’re using the same component to render the results from both queries. So, we need to ensure that the queries and the component are always in sync. If we add or remove a field in one query, we also have to add or remove it from the other one.

Fragments to the rescue

In this short lesson, we’re going to focus on fixing this problem. In one of the first lessons of this course, we covered how to avoid GraphQL code duplication using fragments. To fix our problem, we essentially need to define a fragment and use it for both queries.

We’ve already seen how to use fragments in a query editor. Now, let’s see how we can do this in our React application. We need a new file where our GraphQL queries can go. We should add a fragment that’s defined using the gql tag.

Get hands-on with 1200+ tech skills courses.