šŸ”® Sanity Create is here. Writing is reinvented. Try now, no developer setup

Trouble with `next-sanity` preview hook not displaying draft data in blog post.

9 replies
Last updated: Apr 8, 2021
Maybe I'm missing something in my configuration of the
next-sanity
preview hook, or am misunderstanding how it works, but once set up using
usePreviewSubscription
it should automatically display data in drafts right? Pulling instructions from https://github.com/sanity-io/next-sanity#example-minimal-blog-post-template
I'm trying to test it by editing the title of a blog post without publishing, but am still just getting the published version.
Apr 5, 2021, 4:55 PM
my client config right now:
const config = {
  projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID || '',
  dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || 'production',
  apiVersion: '2021-03-25',
  token: process.env.NEXT_PUBLIC_SANITY_TOKEN,
  useCdn: false,
};
Apr 5, 2021, 4:56 PM
and in my `/blog/[slug].js`:

export default function BlogPost({ post, ...props }) {
  const router = useRouter();
  if (!router.isFallback && !post?.slug) {
    return <FourOhFourPage />;
  }

  const { data: newPost } = usePreviewSubscription(postQuery, {
    params: { slug: <http://props.post?.slug|props.post?.slug> },
    initialData: post,
    enabled: true,
  });

  return <Post post={newPost} {...props} />;
}
Apr 5, 2021, 4:57 PM
My groq query gets
[0]
for the given post slug, but when I remove that in Vision, I can see both the published version, and the
id: 'draft.id-here'
version with my updated title (just added
Test
to the end of the title lol). How do I get the preview client to use that draft version?

  *[_type == 'post' && slug.current == $slug][0] {
    ...,
    'slug': slug.current,
    // other projects here, but not important for this i think
  }
Apr 5, 2021, 5:11 PM
Hmm, looking into it more, it seems to do something when I remove some of the other projections that were references (i.e.
authors[]->{ name }
), but I'm now just getting
null
returned from my
newPost
Apr 5, 2021, 7:07 PM
In your code you've got props.post?.slug should that not be post?.slug?
Apr 5, 2021, 7:57 PM
Ahh good catch! Seems like it was that and maybe some whitespace that was leading to a syntax error
Apr 5, 2021, 8:03 PM
Specifically, when expanding my image asset reference, it didn't like
asset ->
, but
asset->
(no space) fixed it. šŸ¤¦ā€ā™‚ļø
Apr 5, 2021, 8:04 PM
Yes I saw another post saying the new API version doesn't allow for bad syntax any longer.
Apr 5, 2021, 9:23 PM
Specifically, when expanding my image asset reference, it didnā€™t likeĀ 
asset ->
, butĀ 
asset->
Ā  (no space) fixed it.Ā 
Exactly the same! šŸ˜… Thanks, would never have figured it out by myself! šŸ’
Apr 8, 2021, 8:35 PM

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?