Gatsby
Up and Running with Gatsby: Working with Data

Using Site Data in a Static Query

PRO
Outline

From the GraphiQL explorer, copy the siteMetadata query:

query MyQuery {
  site {
     siteMetadata {
        title
         author
        description
       }
    }
}

Open up Header.js and add this import to the top of the file:

import { useStaticQuery, graphql } from "gatsby"

We're going to use the useStaticQuery hook provided by Gatsby to create a static query for this page. Gatsby has two types of queries: static queries and page queries. A single component that's used throughout an application will use a static query, whereas a dynamic page like our About page will use a page query.

Here's the finished component code from the video:

export default () => {
  const data = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            title
          }
        }
      }
    `
  )

  return (
    <div className={headerStyles.headerContainer}>
      <h1>{data.site.siteMetadata.title}</h1>
    </div>
  )
}

Notice a few things here:

  • We're using another tagged template literal to pass in our query.
  • We no longer need the name of the query (it was just MyQuery).
  • We've added the constant for the data above the return of our JSX.
  • We're using the data inside of our JSX to get the title (data.site.siteMetadata.title).

Let's learn about page queries next.

 

I finished! On to the next chapter