Skip to content

Instantly share code, notes, and snippets.

@DSchau
Created August 19, 2019 16:13
Show Gist options
  • Save DSchau/e2941091775a88cd02c67140e020a0b4 to your computer and use it in GitHub Desktop.
Save DSchau/e2941091775a88cd02c67140e020a0b4 to your computer and use it in GitHub Desktop.
Gatsby Node anti-pattern
/*
* This is bad -- it will not "hot reload" with changes
* and leads to confusing bugs
*/
exports.createPages = async function createPages({ actions, graphql }) {
const { data } = await graphql(`
{
allMarkdownRemark {
nodes {
frontmatter {
title
author
date(formatString: "MM-DD-YYYY")
featuredImage {
childImageSharp {
fluid(maxWidth: 800) {
...GatsbyImageSharpFragment
}
}
}
}
fields {
slug
}
html
}
}
}
`)
const postTemplate = require.resolve(`./src/templates/post.js`)
data.allMarkdownRemark.nodes.forEach(node => {
actions.createPage({
component: postTemplate,
path: node.fields.slug,
context: node
})
})
}
/*
* Fetch the minimum data to request a unique resource (e.g. slug, id, etc.)
*/
exports.createPages = async function createPages({ actions, graphql }) {
const { data } = await graphql(`
{
allMarkdownRemark {
nodes {
fields {
slug
}
}
}
}
`)
const postTemplate = require.resolve(`./src/templates/post.js`)
data.allMarkdownRemark.nodes.forEach(node => {
actions.createPage({
component: postTemplate,
path: node.fields.slug,
context: {
slug: node.fields.slug
}
})
})
}
import React from 'react'
import Post from '../components/post'
/*
* This will not hot reload
*/
function PostTemplate({ pageContext }) {
return (
<Post {...pageContext} />
)
}
export default PostTemplate
import React from 'react'
import { graphql } from 'gatsby'
import Post from '../components/post'
function PostTemplate({ data }) {
return (
<Post {...data.markdownRemark} />
)
}
export const postQuery = graphql`
query PostBySlug($slug: String) {
markdownRemark(fields: { slug: { eq: $slug }}) {
frontmatter {
title
author
date(formatString: "MM-DD-YYYY")
featuredImage {
childImageSharp {
fluid(maxWidth: 800) {
...GatsbyImageSharpFragment
}
}
}
}
html
}
}
`
export default PostTemplate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment