petters.io

Drafting in Gatsby

So now that I've committed to writing a blog post a day as I work through challenges, the first challenge I stumbled upon was how to write drafts on this new blog I created using Gatsby.

I found this plugin.

https://www.gatsbyjs.org/packages/gatsby-plugin-draft/

I think for my needs it gets the job done.

yarn add gatsby-plugin-draft

Configure the plugin in gatsby-config.js.

module.exports = {
  plugins: [
    'gatsby-source-filesystem',
    'gatsby-transformer-remark',
    'gatsby-plugin-draft'
  ],
};

and in gatsby-node.js: (NOTE: This step keeps pages from actually generating, you could also just hide them from the index but then if someone stumbled upon your slug uri they would still render :P)

 exports.createPages = async ({ graphql, actions }) => {
    // **Note:** The graphql function call returns a Promise
    // see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise for more info
    const { createPage } = actions;
    const result = await graphql(`
      query {
        allMarkdownRemark(
          filter: { fields: { draft: { eq: false } } } # add
        ){
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
      }
    `)
    
    result.data.allMarkdownRemark.edges.forEach(({ node }) => {
        createPage({
          path: node.fields.slug,
          component: path.resolve(`./src/templates/blog-post.js`),
          context: {
            // Data passed to context is available
            // in page queries as GraphQL variables.
            slug: node.fields.slug,
          },
        })
      })

  }

And to filter them out of the index page, add the same filter to that pages GraphQL page query:

...

export const query = graphql`
  query {
    allMarkdownRemark(
      sort: { fields: [frontmatter___date], order: DESC },
      filter: { fields: { draft: { eq: false } } }

      ) {
      totalCount
      edges {
        node {
          id
          frontmatter {
            title
            date(formatString: "DD MMMM, YYYY")
          }
          fields {
            slug
          }
          excerpt
        }
      }
    }
  }
`

There you have it.

© 2020, Matt Petters