Learn Gatsby · 4/12

The Gatsby Data Layer & GraphQL Fundamentals

8 min read

The Gatsby Data Layer & GraphQL Fundamentals 🍇

Welcome back! So, you've gotten your feet wet with Gatsby, creating pages and getting a feel for the basic structure. Now, it's time to level up and understand one of Gatsby's most powerful features: its data layer. This is where Gatsby truly shines, allowing you to pull data from virtually anywhere and use it to build your site.

1. Introduction to the Centralized Data Node System

Let's start with a common scenario. Imagine you're building a blog. You might have your blog posts in Markdown files, your author information in a JSON file, and maybe some images in a folder. Without a system to manage all of this, you'd have to manually read files, parse them, and figure out how to connect a blog post to its author. It would be like trying to cook a meal where your ingredients are scattered all over the house – some in the kitchen, some in the garage, and maybe one or two under your bed. 🍳

This is the problem Gatsby's data layer solves.

What is the Centralized Data Node System?

At its core, Gatsby's data layer is a system that pulls in data from all your different sources (Markdown files, APIs, databases, etc.) and organizes it into a single, predictable structure. Think of it as a super-organized pantry for your website's data. No matter where the ingredients (data) come from, Gatsby puts them all on clearly labeled shelves, making them easy to find and use.

This "pantry" is a graph of "nodes." A node is simply a single piece of data. A Markdown file could become a node, a user from a JSON file could be another node, and an image could be yet another. Gatsby then creates connections between these nodes. For example, it can link an author node to the blog post nodes they've written.

How does it work under the hood? (The not-so-secret recipe)

During the build process, Gatsby uses "source plugins" to fetch data. For every piece of data fetched, it creates a node object with a unique ID. These nodes are then stored in an internal database. Gatsby also has "transformer plugins" that can take a node of one type and transform it into another, more useful type. For example, gatsby-transformer-remark can take a node representing a Markdown file and transform it into an HTML representation of that file, along with frontmatter data.

This whole system is what allows you to query all your data in a unified way, which brings us to our next topic!

2. GraphQL Crash Course: Queries, Fields, and Arguments 🧑‍🏫

So, we have this beautifully organized pantry of data nodes. Now, how do we ask for specific ingredients? We don't want to grab the entire pantry every time we need to make a single sandwich. This is where GraphQL comes in.

What is GraphQL?

GraphQL is a query language for your API, and in Gatsby's case, for its data layer. It allows you to ask for exactly the data you need, and nothing more. It's like giving a very specific shopping list to a personal shopper who will get you only those items.

The Problem it Solves

With traditional REST APIs, you often have to make multiple requests to different endpoints to get all the data you need for a single component. For instance, to get a blog post and its author, you might first hit a /posts/:id endpoint and then a /users/:userId endpoint. This is called "over-fetching" (getting more data than you need) and "under-fetching" (not getting all the data you need in one go).

GraphQL solves this by giving you a single endpoint where you can send a query that describes the exact data you want.

Queries, Fields, and Arguments

Let's break down a simple GraphQL query.

  • Queries: A query is the operation you send to the GraphQL server to ask for data. It always starts with the query keyword (though it's often optional).

  • Fields: Fields are the specific pieces of data you want to retrieve from an object. If you're asking for a site, you might want its siteMetadata.

  • Arguments: Arguments are how you can specify which data you want to get. For example, if you want to find a specific blog post, you might use an id or a slug as an argument.

Example Time!

Here’s a basic GraphQL query you might write in a Gatsby project:

graphql
query MySiteTitle {
  site {
    siteMetadata {
      title
    }
  }
}

Let's dissect this:

  • query MySiteTitle: We're defining a query and giving it a name, MySiteTitle.
  • site: We're asking for the site object.
  • siteMetadata: Within the site object, we want the siteMetadata object.
  • title: And finally, from siteMetadata, we just want the title field.

The result of this query would be something like:

json
{
  "data": {
    "site": {
      "siteMetadata": {
        "title": "My Awesome Gatsby Site"
      }
    }
  }
}

Notice how the response has the same shape as the query. You get exactly what you asked for! 🤯

3. Exploring Your Data Interactively with GraphiQL

Now you might be wondering, "How do I know what data is available to query?" Do you have to guess? Nope! Gatsby provides an amazing in-browser tool called GraphiQL.

What is GraphiQL?

GraphiQL is an interactive playground for your GraphQL queries. It's like having the entire menu of your data pantry right in front of you, with the ability to test out different combinations before you actually cook with them. When you're running your Gatsby development server (using gatsby develop), you can access it by navigating to http://localhost:8000/___graphql.

Using GraphiQL

When you open GraphiQL, you'll see a few things:

  1. The Query Editor (left pane): This is where you'll write your GraphQL queries. It has autocompletion, so as you start typing, it will suggest available fields and arguments. This is incredibly helpful for discovering your data.
  2. The Play Button (top center): Once you've written a query, you can hit this button to execute it.
  3. The Results Pane (right pane): The results of your query will show up here in JSON format.
  4. The Documentation Explorer (far right): This is your best friend. It's a live documentation of your entire data schema. You can click through it to see all the available query types, fields, and what they return.

A Fun Fact!

GraphiQL was developed by Facebook alongside GraphQL. They wanted a tool that would make it easy for developers to learn and use their new query language, and thus, this awesome interactive environment was born.

Spend some time in GraphiQL. Play around! Try to query for different things. This is the single best way to get comfortable with your site's data structure.

4. Component-Level Data Fetching with the useStaticQuery Hook

So far, we've talked about how Gatsby's data layer works and how to explore it. But how do you actually get that data into your React components?

In Gatsby, there's a distinction between "page queries" and "static queries." Page queries are used for, you guessed it, page components (files in your src/pages directory). But what if you have a component that's not a page, like a header or a footer, and it needs some data?

The Problem

Imagine you have a Header component that needs to display the site's title. You could pass the title down as a prop from the page component, but that can get messy, especially if you have deeply nested components. This is called "prop drilling," and it's generally something to avoid.

The Solution: useStaticQuery

Gatsby provides a React hook called useStaticQuery that allows any component to query the GraphQL data layer.

How to use useStaticQuery

  1. Import it: You'll need to import useStaticQuery and graphql from gatsby.
  2. Write your query: Define your GraphQL query using the graphql tag.
  3. Call the hook: Call the useStaticQuery hook with your query.
  4. Use the data: The hook will return the data you requested, which you can then use in your component.

Let's see it in action!

Here's how you could create a Header component that fetches the site title:

jsx
import React from 'react';
import { useStaticQuery, graphql } from 'gatsby';

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

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

export default Header;

A couple of important rules for useStaticQuery:

  • It doesn't accept variables. The query must be static, meaning you can't pass arguments to it dynamically.
  • You can only have one instance of useStaticQuery in a given file.

And there you have it! You've taken a tour of Gatsby's data layer, from how it organizes data into nodes to how you can query that data with GraphQL and pull it into your components. This is a fundamental part of what makes Gatsby so powerful and flexible.


Further Reading and References

Challenge

Your task is to create a React component, AuthorBio, that fetches specific author data using Gatsby's useStaticQuery hook.

Assume the data is available through a GraphQL query named allAuthorsJson. You need to query for an author with the specific id of "dev_01".

For this author, you must retrieve the following fields:

  • name (string)
  • bio (string)
  • social (an array of objects), where each object contains:
    • platform (string)
    • url (string)

Finally, render the fetched name inside an <h1> tag, the bio inside a <p> tag, and the social links as an unordered list (<ul>), where each list item (<li>) is an anchor tag (<a>) displaying the platform and linking to the url.

Expected result

The final code should be a single React component that correctly implements the following:

  1. Imports: It must import useStaticQuery and graphql from the gatsby package.
  2. GraphQL Query: A const variable holding a GraphQL query written inside the graphql template literal. The query must:
    • Be a static query (not a page query).
    • Target allAuthorsJson.
    • Use a filter argument to select the node where the id field is equal to "dev_01". The syntax should be filter: { id: { eq: "dev_01" } }.
    • Select the name, bio, and social fields. The social field should have sub-fields platform and url.
  3. Hook Implementation: The component must call the useStaticQuery hook, passing the defined GraphQL query to it.
  4. Data Handling: The returned data object from the hook should be correctly destructured to access the author's information (e.g., data.allAuthorsJson.nodes[0]).
  5. JSX Rendering: The component's return statement must render the fetched data within the specified HTML tags:
    • The author's name inside an <h1>.
    • The author's bio inside a <p>.
    • An unordered list <ul> that maps over the social array.
    • Each item in the list must be an <li> containing an <a> tag with its href attribute set to the url and its text content set to the platform.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.