Recipes: Querying Data
Gatsby lets you access your data across all sources using a single GraphQL interface.
Querying data with a Page Query
You can use the graphql tag to query data in the pages of your Gatsby site. This gives you access to anything included in Gatsby’s data layer, such as site metadata, source plugins, images, and more.
Directions
Import
graphqlfromgatsby.Export a constant named
queryand set its value to be agraphqltemplate with the query between two backticks.Pass in
dataas a prop to the component.The
datavariable holds the queried data and can be referenced in JSX to output HTML.
Additional resources
- GraphQL and Gatsby: understanding the expected shape of your data
- More on querying data in pages with GraphQL
- MDN on Tagged Template Literals like the ones used in GraphQL
Querying data with the StaticQuery Component
StaticQuery is a component for retrieving data from Gatsby’s data layer in non-page components, such as a header, navigation, or any other child component.
Directions
- The
StaticQueryComponent requires two render props:queryandrender.
- You can now use this component as you would any other component by importing it into a larger page of JSX components and HTML markup.
Querying data with the useStaticQuery hook
Since Gatsby v2.1.0, you can use the useStaticQuery hook to query data with a JavaScript function instead of a component. The syntax removes the need for a <StaticQuery> component to wrap everything, which some people find simpler to write.
The useStaticQuery hook takes a GraphQL query and returns the requested data. It can be stored in a variable and used later in your JSX templates.
Prerequisites
- You’ll need React and ReactDOM 16.8.0 or later (keeping Gatsby updated handles this)
- Recommended reading: the Rules of React Hooks
Directions
Import
useStaticQueryandgraphqlfromgatsbyin order to use the hook query the data.In the start of a stateless functional component, assign a variable to the value of
useStaticQuerywith yourgraphqlquery passed as an argument.In the JSX code returned from your component, you can reference that variable to handle the returned data.
Additional resources
- More on Static Query for querying data in components
- The difference between a static query and a page query
- More on the useStaticQuery hook
- Visualize your data with GraphiQL
Limiting with GraphQL
When querying for data with GraphQL, you can limit the number of results returned with a specific number. This is helpful if you only need a few pieces of data or need to paginate data.
To limit data, you’ll need a Gatsby site with some nodes in the GraphQL data layer. All sites have some nodes like allSitePage and sitePage created automatically: more can be added by installing source plugins like gatsby-source-filesystem in gatsby-config.js.
Prerequisites
Directions
- Run
gatsby developto start the development server. - Open a tab in your browser at:
http://localhost:8000/___graphql. - Add a query in the editor with the following fields on
allSitePageto start off:
- Add a
limitargument to theallSitePagefield and give it an integer value3.
- Click the play button in the GraphiQL page and the data in the
edgesfield will be limited to the number specified.
Additional resources
- Learn about nodes in Gatsby’s GraphQL data API
- Gatsby GraphQL reference for limiting
- Live example:
Sorting with GraphQL
The ordering of your results can be specified with the GraphQL sort argument. You can specify which fields to sort by and the order to sort in.
For this recipe, you’ll need a Gatsby site with a collection of nodes to sort in the GraphQL data layer. All sites have some nodes like allSitePage created automatically: more can be added by installing source plugins.
Prerequisites
- A Gatsby site
- Queryable fields prefixed with
all, e.g.allSitePage
Directions
- Run
gatsby developto start the development server. - Open the GraphiQL explorer in a browser tab at:
http://localhost:8000/___graphql - Add a query in the editor with the following fields on
allSitePageto start off:
- Add a
sortargument to theallSitePagefield and give it an object with thefieldsandorderattributes. The value forfieldscan be a field or an array of fields to sort by (this example uses thepathfield), theordercan be eitherASCorDESCfor ascending and descending respectively.
- Click the play button in the GraphiQL page and the data returned will be sorted ascending by the
pathfield.
Additional resources
- Gatsby GraphQL reference for sorting
- Learn about nodes in Gatsby’s GraphQL data API
- Live example:
Filtering with GraphQL
Queried results can be filtered down with operators like eq (equals), ne (not equals), in, and regex on specified fields.
For this recipe, you’ll need a Gatsby site with a collection of nodes to filter in the GraphQL data layer. All sites have some nodes like allSitePage created automatically: more can be added by installing source and transformer plugins like gatsby-source-filesystem and gatsby-transformer-remark in gatsby-config.js to produce allMarkdownRemark.
Prerequisites
- A Gatsby site
- Queryable fields prefixed with
all, e.g.allSitePageorallMarkdownRemark
Directions
- Run
gatsby developto start the development server. - Open the GraphiQL explorer in a browser tab at:
http://localhost:8000/___graphql - Add a query in the editor using a field prefixed by ‘all’, like
allMarkdownRemark(meaning that it will return a list of nodes)
- Add a
filterargument to theallMarkdownRemarkfield and give it an object with the fields you’d like to filter by. In this example, Markdown content is filtered by thecategoriesattribute in frontmatter metadata. The next value is the operator: in this caseeq, or equals, with a value of ‘magical creatures’.
- Click the play button in the GraphiQL page. The data that matches the filter parameters should be returned, in this case only sourced Markdown files tagged with a category of ‘magical creatures’.
Additional resources
- Gatsby GraphQL reference for filtering
- Complete list of possible operators
- Learn about nodes in Gatsby’s GraphQL data API
- Live example:
GraphQL Query Aliases
You can rename any field in a GraphQL query with an alias.
If you would like to run two queries on the same datasource, you can use an alias to avoid a naming collision with two queries of the same name.
Directions
- Run
gatsby developto start the development server. - Open the GraphiQL explorer in a browser tab at:
http://localhost:8000/___graphql - Add a query in the editor using two fields of the same name like
allFile
- Add the name you would like to use for any field before the name of the field in your GraphQL schema, separated by a colon. (E.g.
[alias-name]: [original-name])
- Click the play button in the GraphiQL page and 2 objects with alias names you provided should be output.
Additional resources
- Gatsby GraphQL reference for aliasing
- Live example:
GraphQL Query Fragments
GraphQL fragments are shareable chunks of a query that can be reused.
You might want to use them to share multiple fields between queries or to colocate a component with the data it uses.
Directions
- Declare a
graphqltemplate string with a Fragment in it. The fragment should be made up of the keywordfragment, a name, the GraphQL type it is associated with (in this case of typeSite, as demonstrated byon Site), and the fields that make up the fragment:
- Now, include the fragment in a query for a field of the type specified by the fragment. This includes those fields without having to declare them all independently:
Note: Fragments don’t need to be imported in Gatsby. Exporting a query with a Fragment makes that Fragment available in all queries in your project.
Fragments can be nested inside other fragments, and multiple fragments can be used in the same query.
Additional resources
- Example repo using fragments
- Gatsby GraphQL reference for fragments
- Gatsby image fragments
- Example repo with co-located data
Querying data client-side with fetch
Data doesn’t only have to be queried at build time and remain solely static. You can query data at runtime the same way you can fetch data in a regular React app.
Prerequisites
- A Gatsby Site
- A page component, such as
index.js
Directions
- In a file with a React component defined, like a page in
src/pagesor a layout component, import React hooks foruseStateanduseEffect.
- Inside the component, wrap a function to fetch data in a
useEffecthook so it will asynchronously retrieve data when the component mounts in the browser client. Then,awaitthe result with thefetchAPI, and call the set function from theuseStatehook (in this casesetStarsCount) to save the state variable (starsCount) to the data returned fromfetch.
Additional resources
- Guide on client-data fetching
- Live example site using this example