Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Emeruche Ikenna
Emeruche Ikenna

Posted on • Originally published atcoleruche.com on

     

Implementing a Draft Feature in a Gatsby Blog

Hello there, fellow Gatsby blog owner!

Recently, I’ve found myself thinking and writing about GatsbyJS. Mostly because, like Bootstrap and React, it’s one of the best thing that has happened to me since I started learning front-end development. And now I’m going to share something (not-so-new) I learnt.

When I started out building my portfolio-cum-blog website with Gatsby and actually started writing, I came across an issue. For someone who also writes onDev.to - where you can start writing out an article, only todraft it and move onto a new one - I got a bit disappointed why uptil now, Gatsby’sblog starter does not include a built-in functionality of saving drafts and only publishing posts you set as “published”, as seen on Dev.to.

There are other alternatives to this which I found online. Links to them will be listed at the end of this article.Also this article assumes you’re running a blog powered by Gatsby’sgatsby-starter-blog

My first thought on how to solve this was looking for the chunk of code that handles creation of pages from Markdown files, and I found this ingatsby-node.js:

exports.createPages=async({graphql,actions})=>{const{createPage}=actionsconstblogPost=path.resolve(`./src/templates/blog-post.js`)constresult=awaitgraphql(`      {        allMarkdownRemark(          sort: { fields: [frontmatter___date], order: DESC }          limit: 1000        ) {          edges {            node {              fields {                slug              }              frontmatter {                title              }            }          }        }      }    `)if(result.errors){throwresult.errors}// Create blog posts pages.constposts=result.data.allMarkdownRemark.edgesposts.forEach((post,index)=>{constprevious=index===posts.length-1?null:posts[index+1].nodeconstnext=index===0?null:posts[index-1].nodecreatePage({path:post.node.fields.slug,component:blogPost,context:{slug:post.node.fields.slug,previous,next,},})})}
Enter fullscreen modeExit fullscreen mode

As you can rightly guess, the pages are created from data gotten with theallMarkdownRemark query. This is where we can work our magic.

Right next to thesort command, we can add our ownfilter rule to get only posts we mark as published. To do this, you should add a variablepublished in your articles’ frontmatter, which is set totrue orfalse depending on the status of the article. For example, to set an article as a draft (i.e unpublshed) add this to the file’s front matter:published: true.

Now that we have a way of marking posts as ready to be published or not, we get back to the GraphQL query and change it like so:

exports.createPages=async({graphql,actions})=>{const{createPage}=actionsconstblogPost=path.resolve(`./src/templates/blog-post.js`)constresult=awaitgraphql(`      {        allMarkdownRemark(sort: {fields: frontmatter___date, order: DESC}, filter: {frontmatter: { published: {eq: true} }}, limit: 1000)        ...        // your other code        ...        slug: post.node.fields.slug,        previous,        next,      },    })  })}
Enter fullscreen modeExit fullscreen mode

This change ensures that Gatsby only filters out posts we set it’s published variable totrue in it’s fromtmatter.Please note to add this rule to wherever else you are doing some tasks with your posts, eg when in yoursrc/pages/index.js file, where there’s a similar query for listing out your articles, and also if you’re creating your RSS feed withgatsby-plugin-feed.

As I stated before I started, there are other alternatives around the web for this. Check out this method byJanosh and this one byChase Adams. Use whichever method you prefer, and if you have your own super cool method for this, please share with us some code snippets in the comment sections or paste the link to the article.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
gughog profile image
Gustavo Oliveira
Front End Developer and in love with Javascript and Lua lang.

Thank you, man! It was really helpful! 👍

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Blockchain (Solidity) and Frontend software engineer.
  • Location
    Nigeria
  • Work
    Software Engineer II at Crossover
  • Joined

More fromEmeruche Ikenna

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp