👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Issue targeting individual blog posts on portfolio site resolved with GraphQL query fix

2 replies
Last updated: Jun 18, 2022
Hello Sanity Squad. 👋
I am having some issue trying to target individual blogs post on my
portfolio site . When clicking on “First Blog”, url read correct(
…/blog/first-blog
) but content is from Second Blog.My guess would be that query in
templates/blog.js is not correct, because it is not targeting individual blogs?

//templates/blog.js

import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/layout'
import { PortableText } from '@portabletext/react'

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
Here is the main
pages/blog.js if needed for reference.
Lastly, my Gatsby + Sanity setup may be kind of weird because I previously was using Contentful and now migrating to Sanity.
😀My apologies for the long post and thanks in Advance!
Jun 17, 2022, 10:59 PM
I was able to figure it out by parsing through sanity-gatsby-combo demo. In templates/blog.js I had to create an
$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
    }
  }
`
...
Now clicking on either Second or First blog will render correct content:
https://deploy-preview-85--simonxcode.netlify.app/blog

Note to self: Learn graphQL fundamentals, variables, mutations to understand exactly what the heck is going on! 👀
Jun 18, 2022, 5:10 AM
Kudos for figuring it out!
Jun 18, 2022, 9:00 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?