⚠️ This lesson is retired and might contain outdated information.

Fetch and Query Data at Build Time in Gatsby

Khaled Garbaya
InstructorKhaled Garbaya

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

In order to fetch data at build time, you can use a source plugin or source data yourself. In our case we'll be using the gatsby-source-graphql plugin. It allow us to connect arbitrary GraphQL APIs to Gatsby’s GraphQL, in this case Contentful.

In this lesson, you will learn how to load data from an external service and query it in you rgatsby project using GraphQL

Instructor: [0:00] One of the common way to load data into Gatsby is to source that data from an external service through an API. In my case here intentful, I used it to rebuild our Pokémon data.

[0:11] You can see here I have a Cournot model with a name, slug, and power. If I go to content, you can see here I filled in the same data that we had hard coded as JSON.

[0:23] Going back to our project, since we're going to load this data via GraphQL, we need to install the gatsby-source-graphql. To do that, first let's install it as a dependency. Let's add the plugin and configure it inside of Gatsby-config.

[0:40] Here, I'm loading the source-graphql plugin and I'm giving it a type name of Contentful. I am connecting Gatsby to my GraphQL endpoint on the Contentful side. Here, I'm adding my API key. The API key is inside of this in the development file. There's a plenty of documentation on how you can get this API token from Contentful.

[1:10] Last thing, we need to load this environment variable. This can be done by requiring .env and providing a path for it. Now this is done, let's go to Gatsby-node.

[1:23] First thing here, let's extract the GraphQL and change this function to async function. Instead of using this hard-coded data, we will be loading the data from our GraphQL source data. Let's delete this one. In here, let's have const result and we will do GraphQL and pass in the query.

[1:55] First thing to start the query, we need to have the curly brackets. Since we called the field name Contentful here, we'll need to provide Contentful here for Gatsby to know that this is coming from Contentful. Inside of here, we need to query for the Pokémon collection. Inside of the Pokémon collection, we have items. Inside of items, we need slug and name.

[2:24] Here, we need to await the GraphQL. Instead of Pokémons, we need to do result.data.contentful.pokemonCollection.items and then we can look through them. Let's test this out. Let's run develop. Then here, if we hit Refresh or go home, Pokémons, go to one of the pages, and you can see our pages are still created in here.