In this article, we will learn how to create, access, and render data in the Gatsby application.
There are two options to store data in Gatsby.
The setup for both options is similar:
We first need to sign up or login into our Contentful account: https://www.contentful.com/.
After logging in, we can create a new project, create a content type and add content.
For example, we create 3 sample products that have:
You can learn more about Contentful at Contentful Learning Center.
We need to install Contentful plugin to pull content types and data into Gatsby from Contentful.
npm install gatsby-source-contentful
// In gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: `your_space_id`,
// Learn about environment variables: https://gatsby.dev/env-vars
accessToken: `YOUR_ACCESS_TOKEN`,
},
},
],
};
To protect your accessToken, we need to use Environment Variables.
.env.development
file and fill in your token.In this example, I name the variable ACCESS_TOKEN.
ACCESS_TOKEN=YOURTOKEN
Because the .gitignore file already ignores .env*
, so our ACCESS_TOKEN variable won’t be pushed to Github
// In gatsby-config.js
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
});
module.exports = {
plugins: [
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: `your_space_id`,
// Learn about environment variables: https://gatsby.dev/env-vars
accessToken: process.env.ACCESS_TOKEN,
},
},
],
};
We can view our Contentful query in GraphQL.
{
allContentfulProduct {
nodes {
id
price
title
slug
image {
fluid {
...GatsbyContentfulFluid
}
}
}
}
}
The field name in GraphiQL will match exactly what we have in the Content model.
Here is an example of a Product page.
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import styles from "../css/products.module.css"
import Image from "gatsby-image"
const Product = ({ data }) => {
const {
allContentfulProduct: { nodes: products },
} = data
return (
<Layout>
<section className={styles.page}>
{products.map(product => {
return (
<article key={product.id}>
<Image fluid={product.image.fluid} alt={product.title}></Image>
<h3>
{product.title} <span>${product.price}</span>
</h3>
</article>
)
})}
</section>
</Layout>
)
}
export const query = graphql`
{
allContentfulProduct {
nodes {
id
price
title
slug
image {
fluid {
...GatsbyContentfulFluid
}
}
}
}
}
`
export default Product