Unlock the Power of Gatsby: A Deep Dive into Data Fetching

When building a Gatsby application, data is essential to make it functional. While we can add data directly within the application component, a more maintainable approach is to store data outside of the component and allow Gatsby to fetch it at build time. In this article, we’ll explore how to fetch data from a Gatsby configuration file and external sources using GraphQL.

Setting Up a Gatsby Project

To get started, let’s create a new Gatsby project using the following command:

gatsby new gatsby-starter-data-fetching

Next, navigate into the project directory and install the required dependencies:

cd gatsby-starter-data-fetching
npm install

Open the project in your favorite code editor and run gatsby develop to start the development server.

Fetching Data from the SiteMetadata Object

In any web project, we often have reusable data that we want to access across our site. With Gatsby, we can store this data in the siteMetadata object within the gatsby-config.js file. This object is a great place to store static data like the hero title and page description.

Let’s update the siteMetadata object to include some sample data:
js
module.exports = {
siteMetadata: {
title: 'My Blog',
description: 'This is my blog',
twitterHandle: '@mytwitterhandle',
author: 'John Doe',
},
};

To fetch this data and use it in our application components, we’ll need to understand Gatsby’s GraphQL data layer.

Understanding Gatsby’s GraphQL Data Layer

Gatsby has a built-in data layer powered by GraphQL, which allows us to query data from various sources. The siteMetadata object is automatically pulled into the data layer, making it accessible via GraphQL queries.

Let’s explore the data layer using GraphiQL, a tool that allows us to construct and execute GraphQL queries. Open GraphiQL by navigating to http://localhost:8000/_graphql in your browser.

Querying the SiteMetadata Content

In GraphiQL, we can construct a query to fetch the siteMetadata content. Let’s create a query that fetches the title, description, and Twitter handle:
graphql
query {
site {
siteMetadata {
title
description
twitterHandle
}
}
}

Execute the query, and you’ll see the response in JSON format.

Using a Page Query and StaticQuery

To load data using the GraphQL query, we can use either a page query or StaticQuery. In this example, we’ll use the useStaticQuery Hook to fetch data in our component.

Let’s create a Hero component that fetches the title, description, and Twitter handle using the useStaticQuery Hook:
“`jsx
import { useStaticQuery, graphql } from ‘gatsby’;

const Hero = () => {
const data = useStaticQuery(graphql
query {
site {
siteMetadata {
title
description
twitterHandle
}
}
}
);

return (

{data.site.siteMetadata.title}

{data.site.siteMetadata.description}

Twitter Handle: {data.site.siteMetadata.twitterHandle}

);
};
“`
Fetching Data from the File System

So far, we’ve learned how to fetch data from the siteMetadata object. Now, let’s explore how to fetch data from the file system.

To fetch data from the file system, we’ll need to create a source plugin that communicates with the file system and pulls data into the Gatsby data layer. In this example, we’ll create a posts folder with some sample MDX files.

Creating the Blog Post MDX Files

Create a posts folder in the root directory, and add some sample MDX files:
“`md

// posts/first-post.mdx

title: First Post

date: 2022-01-01

This is my first post.

// posts/second-post.mdx

title: Second Post

date: 2022-01-02

This is my second post.
“`
Querying the File System Data

To query the file system data, we’ll need to install the gatsby-source-filesystem and gatsby-plugin-mdx plugins:

npm install gatsby-source-filesystem gatsby-plugin-mdx

Add the plugins to the gatsby-config.js file:
js
module.exports = {
//...
plugins: [
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'posts',
path: `${__dirname}/posts`,
},
},
'gatsby-plugin-mdx',
],
};

Restart the development server, and refresh GraphiQL. You should see additional nodes added by the plugins.

Rendering the Blog Posts

Let’s create a Blog component that fetches all blog posts using the allMdx field:
“`jsx
import { useStaticQuery, graphql } from ‘gatsby’;

const Blog = () => {
const data = useStaticQuery(graphql
query {
allMdx {
nodes {
id
frontmatter {
title
date
}
}
}
}
);

return (

{data.allMdx.nodes.map((post) => (

{post.frontmatter.title}

{post.frontmatter.date}

))}

);
};
“`
Conclusion

In this article, we’ve learned how to fetch data from the siteMetadata object and the file system using GraphQL. With Gatsby, we can fetch data from various sources using their specific plugins. By understanding how to fetch data, we can build powerful and scalable applications with Gatsby.

Leave a Reply

Your email address will not be published. Required fields are marked *