How to use GraphQL in Gatsby

In this section, we’ll learn how to load data directly to our component using GraphQL.

I. What is GraphQL?

GraphQL is a query language for our API, describing how to ask for data, and it is generally used to load data from a server to a client.

With Gatsby, the queries can be generated from a tool called GraphiQL, which is available at http://localhost:8000/\_\_\_graphql after running gatsby develop.

Example We create dummy data in gatsby-config.js

module.exports = {
  siteMetadata: {
    title: "Gatsby tutorial",
    description: "Hello",
    author: "@hatrcode",
    data: ["item 1", "item 2"],
    person: {name:"Anna", age:20}
  },
}

In GraphiQL IDE, we can generate the queries by clicking on the boxes on the Explorer tab.

query {
    site {
        siteMetadata {
            title
            description
            author
            data
            person {
                name
                age
            }
        }
    }
}

We can also test the query to see what they return by hitting the play button on the top left.

We can then export our codes by using the Code Exporter button.

II. Alias in GraphQl

We can provide an alias for any field with this syntax.

alias-name: old-name

For example

query {
    site {
        info: siteMetadata {
            title
            description
            author
            data
            person {
                name
                age
            }
        }
    }
}

III. Render data

Data can be queried inside pages or components using one of these options:

  • useStaticQuery Hook
  • StaticQuery component
  • pageQuery component

1. useStaticQuery

useStaticQuery is a hook that takes a GraphQL query and returns your data.

Import

To use useStaticQuery, we need to import useStaticQuery and graphql

import { useStaticQuery, graphql } from "gatsby"

As graphQl is a tag template, so we set up template literal and pass in our query.

const getData = graphql`
    query {
      site {
        info: siteMetadata {
          title
          description
          author
          data
          person {
            name
            age
          }
        }
      }
    }
`

Invoke

Once we set up our query, we invoke useStaticQuery and pass in a variable.

const { data } = useStaticQuery(getData)

We can also destructure the object.

const {
        site: {
            info: {
                title,
                person: {name},
            },
        },
    } = useStaticQuery(getData)

Render data

We then render the data.

import React from "react"
import { useStaticQuery, graphql } from "gatsby"

const getData = graphql`
    query {
      site {
        info: siteMetadata {
          title
          description
          author
          data
          person {
            name
            age
          }
        }
      }
    }
`

const Content = () => {
    const {
        site: {
            info: {
                title,
                person: {name},
            },
        },
    } = useStaticQuery(getData)

    return (
        <div>
            <h1>Title: {title}</h1>
            <h2>Name: {name}</h2>
        </div>
    )
}

export default Content

Note:

If we use const { data } = useStaticQuery(getData), in the render, we need to drill down the property that we’re looking for:

return (
    <div>
        <h1>Title: {data.site.info.title}</h1>
        <h2>Name: {data.site.info.name}</h2>
    </div>
)

2. StaticQuery

StaticQuery is a component and has two props.

  • query
  • render

render has a function that returns what will be rendered on the page.

import React from "react"
import { StaticQuery, graphql } from "gatsby"

const ComponentName = () => (
  <StaticQuery
    query={graphql`
      query {
        site {
          info: siteMetadata {
            title
            description
            author
            data
            person {
              name
              age
            }
          }
        }
      }
    `}
    render={data => <h4>data.site.info.description</h4>}
  ></StaticQuery>
)

export default ComponentName

To get the code above, we use the Code Exporter button, then choose Static Query. We then can adjust what we want to render

3. pageQuery

To set up a pageQuery, we must create a page in the src/pages folder. For example, we create an example.js page.

Step 1: Import GraphQL

import { graphql } from "gatsby"

Step 2: Set up a query and export the variable.

export const query = graphql`
  query {
    site {
      info: siteMetadata {
        title
        description
        author
        data
        person {
          name
          age
        }
      }
    }
  }
`

Step 3: Display props

import React from 'react'
import { graphql } from "gatsby"
import Layout from "../components/layout"

const examples = ({ data }) => {
    const {
        site: {
            info: {author},
        },
    } = data

    return (
        <Layout>
            <h1>Hello world</h1>
            <h5>Author: {author}</h5>
        </Layout>
    )
}

export const query = graphql`
  query {
    site {
      info: siteMetadata {
        title
        description
        author
        data
        person {
          name
          age
        }
      }
    }
  }
`

export default examples