How to make a front-end GraphQL query on a page in GatsbyJS
A step by step tutorial on making a front-end GraphQL query in GatsbyJS. Github repository included.
Please note that GraphQL page queries only work on pages that are programmatically created or which sit within the Pages folder under your src folder within your GatsbyJS project.
The following tutorial walks you through how to make a front-end GraphQL page query in GatsbyJS. The tutorial can be reproduced using our open source starter project, available in the link below.
If you are curious on how to make GraphQL backend queries, programmatically create pages in Gatsby or to create and make use of reusable front-end GraphQL queries, please consult the tutorials below.
Tutorial
Please note that this tutorial makes use of our Open Source project. We recommend checking out the tutorial/backend-fragments branch and carrying out the steps outlined below.
git clone git@github.com:delasign/gatsbyjs-typescript-starter.git
An example of this tutorial with a frontend fragment can be found at the tutorial/frontend-fragments branch as well as in the link below.
Step One: Import GraphQL from Gatsby
At the top of your page, import graphql from gatsby using the following line.
import { graphql } from "gatsby";
Step Two: Construct & Export the Query
Please note that GraphQL page queries only work on pages that are programmatically created or which sit within the Pages folder under your src folder within your GatsbyJS project.
At the bottom of your page, construct and export your graphql query.
If you wish to use data passed down from the backend within your query, use a $. For example, we programatically generated pages using the GatsbyJS backend and passed down the slug which we used to narrow down our query by implementing it using $slug.
Sample code of the full tutorial is found at the gist at the bottom of the page.
Step Three: Consume data
The data from your GraphQL page query will be made available in the props under data.
We recommend that you add this to your props typescript type to avoid errors and printing it onto the console or on the page to verify
The code for the full solution is provided below.
Code for our solution
Any Questions?
We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.