As we have got to know that Gatsby has built in GraphQL, we will learn this time how to ask Gatsby to request data from GraphQL. We will ask for the data that we wish to populate into our blog. For simplicity sake we will only target on the title and tagline. Eventually we will dive deep into into it later when we talk about plugins.

First we need to modify our gatsby-config.js file and add sitemap information into it. Below you will see that I have added a tag called SiteMetadata and inside the json object it contains title and tagline.

If we wish to view this data we can go to our trusty graphql site that Gatsby has created for us (http://localhost:8000/___graphql). We can query the data in the query field like below and we will get back a json object with the information.



How to get the data into our page

You are like great we have graphql but how do I get this data into my page? That is where graphql query inside our code comes in handy. Let open up our index.js that we have been working on and modify it to include graphql and we can also query it like the code below.

NOTE: Query only works in pages

NOTE: The single right tick quotes that encapsulates the query

We have also passed in {data} as a parameter into the Home function, we are able to print the data with the {} brackets. e.g {}, it is basically the same way we see the data in graphql UI.

How to share the data to components then?

One way to share data to component is to pass it down but then it becomes ugly quite soon, therefore there is actually another way to query data with components that is to use staticQuery, since page query are not supported in components. Let’s see that in action for our Layout component we made. Open the file components/layout.js

As you have noticed I have imported useStaticQuery and graphql into my javascript. I have also declared a const variable called data and have used it to pass the data to my header component and footer component. Again you can use the same query inside of component the only difference is that you can see above is I have wrapped it around useStaticQuery.


We talked about using Query to get data from GraphQL for our Gatsby site, where Query are only allowed in pages. We also talked about how we can use staticQuery to get data inside our components. In our next section we will talk about using source plugin with GraphQL power to get data from local filesystems, such that we can eventually read our blog post.