Organise Gatsby Queries with GraphQL Fragments

by Jack Pritchard

Hey! Just so you know, this article is over 2 years old. Some of the information in it might be outdated, so take it with a grain of salt. I'm not saying it's not worth a read, but don't take everything in it as gospel. If you're curious about something, it never hurts to double-check with a more up-to-date source!

I'm obsessed with organising code and keeping my files short, module and most importantly reusable. While arranging any site using atomic design principles may help keep your components stay organised, it's another story when you look at storing how you obtain data as a reusable pattern.

A real-world challenge which I am currently facing in a project involves creating a page that queries a GraphQL data type within Gatsby.

Gatsby, GraphQL and the Static Query

#

Normally to create a static query for a page in Gatsby you'd import React and two imports including StaticQuery and Graphql from the Gatsby package itself.

Then you'd write a component similar to the following -

return (
<StaticQuery
query={graphql`
query DataTypeName {
allDataType {
nodes {
fieldOne
fieldTwo
fieldThree
}
}
}
`}
render={query => <PageComponent query={query} {...props} />}
/>
);

Now you have the PageComponent being rendered with the query results available as a prop. Creating a page and component using this method isn't an issue when you have a relatively small number of fields to query in GraphQL. However, the site that I'm working on has over one hundred fields available to query.

Including over one hundred fields in my component file seems overkill for a static query, not to mention the fields I reference my change in the future or be required in another component. Repeating yourself when coding is never ideal, and fortunately, Gatsby provides a way of implementing GraphQL queries which are reusable.

This new method includes the use of GraphQL fragments.

GraphQL Fragments

#

As defined by GraphQL.org - “Fragments let you construct sets of fields, and then include them in queries where you need to.”

GraphQL fragments aren't limited to the context of Gatsby, they can be used in almost any application that uses GraphQL. Read more about the information surrounding GraphQL fragments at the official GraphQL website under the topic of queries - https://graphql.org/learn/queries/#fragments

Creating our GraphQL Fragment

#

In the context of Gatsby, you are required to store these fragments in a specific directory within the src folder of the site. The directory will need to be a folder named 'src/graphql-fragments'. Within this folder, you'd compose a GraphQL query fragment within a file named similar to 'LocationFields.jsx' or any naming pattern that suits your site. Within the file, you'd create a code structure similar to this -

import { graphql } from 'gatsby';
export const LocationFragment = graphql`
fragment LocationFragment on Location {
BUILT_FORM
BUILT_FORM_UID
ENVIRONMENT_IMPACT_CURRENT
ENERGY_CONSUMPTION_CURRENT
CO2_EMISSIONS_CURRENT
CO2_EMISSIONS_POTENTIAL
CONSERVATORY_TYPE
}
`;

Once you start/restart your Gatsby development server you will now have access to this Fragment in any of your page or component files.

Using Our GraphQL Fragment

#

To use the GraphQL Fragment you will need to reference it using triple dots to spread the Fragment, along with the name of the Fragment itself. E.g. -

export default props => (
<StaticQuery
query={graphql`
query LocationInfo {
allLocation {
nodes {
...LocationFragment
}
}
}
`}
render={query => <HomePageWrapper query={query} {...props} />}
/>
);

The Fragment example I've provided only lists seven fields, but you can go on and list tens, hundreds or thousands of fields to query. In my real-world challenge, I've included 142 fields in my query!

As you can see, this new syntax shaves off lines of code in our page file, keeping a focus on what the component renders to the user, and less on the querying of data. Anyone familiar with fragments will easily be able to understand the logic of the file, and newcomers should get some indication of what the logic may include; this is due to the familiarity of the spread syntax in combination with a clearly labelled name for our Fragment.

Want More?

#

Interested in GraphQL, Gatsby or React? Follow me on Twitter @whatjackhasmade and reach out to discuss more on the technologies, or follow me for news related to the topics.