How to query Sanity blog post with Gatsby

Viewed 101

I have a Gatsby site set up with Sanity CMS for blogging. Current I am unable to properly target individual blog post(clicking on "First Blog" link will render content from "Second Blog").

Current Behavior: screenshot of current behavior

My guess would be this is due to how graphQL query is setup in template/blog.js? If so, what changes would need to be made to properly target individual blog post?

//templates/blog.js
...
export const query = graphql`
  query {
    sanityPost {
      id
      slug {
        current
      }
      title
      publishedAt(formatString: "MMM Do, YYYY")
      _rawBody
    }
  }
`

const BlogPost = ({ data }) => {
  return (
    <Layout>
      <h1>{data.sanityPost.title}</h1>
      <p>{data.sanityPost.publishedAt}</p>
      <PortableText value={data.sanityPost._rawBody} />
    </Layout>
  )
}

export default BlogPost

Lastly, the code source for the blog page itself can be found here: blog.js and working sample here: demo.

Thanks in advance!

1 Answers

I was to figure it out by parsing through sanity-gatsby-combo demo. In templates/blog.js I needed to create $id variable to target the id of every post.

//templates/blog.js

...
export const query = graphql`
  query($id: String!) {
    sanityPost(id: {eq: $id}){
      id
      slug {
        current
      }
      title
      publishedAt(formatString: "MMM Do, YYYY")
      _rawBody
    }
  }
`
...

FWIW here is the request/response:

graphQL request/response

Working sample with correct routing to individual blogs: https://deploy-preview-85--simonxcode.netlify.app/blog

Note to self: learn graphQL fundamentals!

Related