Skip to content

How to Use GraphQL in Gatsby

Gatsby/ (Posted on )

Gatsby uses GraphQL to manage data of your website. At build-time, Gatsby gathers data from many different sources and builds a GraphQL schema. It serves as a central data source that you can perform queries on from anywhere in your code.

You can avoid GraphQL while working with Gatsby, but you would miss out on many benefits, such as:

  • ability to transform raw data to structured data that is easy to work with
  • improved performance
  • access to many plugins

How to Query Data in Page Components

You can use siteMetadata inside gatsby-config.js to specify data about your website. Gatsby will automatically pull this data into the GraphQL schema.

// gatsby-config.js

module.exports = {
  siteMetadata: {
    title: 'Awesome Website',
    description: 'This is a description about this website.',
  },
};

This, of course, is a basic example and there are many different sources to grab data from.

Now that GraphQL has some data available, you can write a query to retrieve it in any page you want.

import React from 'react';
import { graphql } from 'gatsby';

const IndexPage = ({ data }) => {
  return (
    <>
      <h1>{data.site.siteMetadata.title}</h1>
      <p>{data.site.siteMetadata.description}</p>
    </>
  );
};

export default IndexPage;

export const query = graphql`
  query IndexPageQuery {
    site {
      siteMetadata {
        title
        description
      }
    }
  }
`;

There are a few things to keep in mind here:

  1. You must export the query
  2. The name of the variable, query in this case, can be anything you want
  3. You can also change the IndexPageQuery name as you please
  4. You must provide a data prop to the component to access the queried data

Querying Data in Regular Components

In the previous section you queried data in a page component. What if you want to make a reusable component that queries data which you want to reuse in every page?

You must use the useStaticQuery hook to run queries outside of page components.

Create a regular component in src/components folder and make these changes to run the query.

import React from 'react';

import { graphql, useStaticQuery } from 'gatsby';

const Header = () => {
  const data = useStaticQuery(graphql`
    query HeaderQuery {
      site {
        siteMetadata {
          title
          description
        }
      }
    }
  `);

  return (
    <header>
      <h1>{data.site.siteMetadata.title}</h1>
      <p>{data.site.siteMetadata.description}</p>
    </header>
  );
};

export default Header;

Now you can reuse this component with the queried data in any page you want.

import Header from '../components/Header';

const IndexPage = () => {
  return (
    <>
      <Header />
      <p>Page content</p>
    </>
  );
};

Using Queries in createPages API

You can query data while you are creating pages programmatically using the createPages API.

Gatsby runs the createPages after the GraphQL schema has been completely built.

In your gatsby-node.js, destructure the graphql function and use it to query any data you want.

exports.createPages = async ({ graphql, actions }) => {
  const result = await graphql(`
    query MetadataQuery {
      site {
        siteMetadata {
          title
          description
        }
      }
    }
  `);

  console.log(result.data.site.siteMetadata);
};

Exploring GraphQL in Your Browser

Gatsby comes with GraphiQL installed. It is an interactive GraphQL IDE that you can use in your browser. You need to run gatsby develop and then you can access it by opening http://localhost:8000/___graphql.

You can use GraphiQL to explore your site’s GraphQL schema. You can build queries using its graphical interface and run them to see the resulting data.

GraphQL Playground is an alternative to GraphiQL. It is similar, but comes with some new features. To use it, you need to run GATSBY_GRAPHQL_IDE=playground gatsby develop in your terminal. You can then open the same URL and you should see a different IDE.

References