How to Write Reusable Queries in Gatsby
It is common to request the same fields in many GraphQL queries. This can lead to a lot of duplicate code.
As a solution, you can use GraphQL fragments to save frequently used queries.
Prerequisites
You should know how to write queries in Gatsby. Read my article How to Use GraphQL in Gatsby if you need to learn that first.
Source Code
If you want to see the code used in a project, checkout this GitHub repository I made to show how to use fragments.
Step 1 — Defining a Fragment
You can create a fragment in any file that Gatsby is aware of. At build-time, Gatsby goes through all source code and finds them.
The following example creates a fragment inside src/fragments.js
named PostInfo
. It uses title
and author
fields from GraphQL Post
object type, but you can add as many fields from Post
as you want.
// src/fragments.js
import { graphql } from 'gatsby';
export const fragment = graphql`
fragment PostInfo on Post {
title
author
}
`
The name of the exported variable is unimportant. You can rename const fragment
to something else.
You specify the fragment’s name after the fragment
keyword (line 6). You can choose any name you want, but fragment names must be unique. Don’t use PostInfo
again in another fragment.
The Post
is the name of GraphQL object type. This can be anything that you can query data from.
Step 2 — Using the Fragment
Fragments are globally available to any GraphQL query. You don’t need to “import” them anywhere. To use a fragment, you need to insert its name in a query.
Whenever you want to get title
and author
from Post
, use the fragment. Insert its name in place of the fields and add ...
in front of it.
// src/pages/blog.js
export const query = graphql`
query PostList {
allPost {
nodes {
...PostInfo
}
}
}
`;
You can query more fields together with the fragment.
// src/templates/blog-post.js
export const query = graphql`
query Post {
allPost {
nodes {
...PostInfo
content
}
}
}
`;
This query will retrieve the properties specified in PostInfo
fragment and content
.
Summary
You can reuse parts of queries by using fragments. They are globally available in your code. To use them, substitute the fields in the query with a fragment — ...FragmentName
.
Don’t forget that you can see the full source code in this GitHub repository.