Join live – Get insights, tips, + Q&A from Sanity developers on our latest releases

Issue with basic groq query in Sanity not returning expected results.

6 replies
Last updated: Sep 19, 2023
I'm having issues doing a basic groq query with Sanity.
I've made an Astro SSR website that I want to use sanity with. I've made a page that accepts dynamic params, in this case the post's slug. However, when I try to use the following query, it returns null:

const post = await useSanityClient().fetch(
  `*[_type == "post" && slug.current == ${slug}][0]`
Even though the slug param is not undefined, and if I fetch all posts, I can see my post with the same slug as the one I am trying to compare it to. I'm quite new to Sanity and GROQ, so there must surely be a key factor I am missing in this query, but I just can't see it. Anyone who might know why it is not able to fetch the post?
Sep 19, 2023, 9:21 PM
Are you sure that
is defined?
Sep 19, 2023, 9:27 PM
Yes, I have tested multiple times. I also left out the fact that I am getting to this page by clicking a link on a collection page, and I build the link using the slug from every post.
Here's me console-logging both the param and post values:
Sep 19, 2023, 9:30 PM
Then the issue is likely that you’re using a template literal instead of passing params into your query.
Sep 19, 2023, 9:32 PM
that does indeed seem to be the issue 🤦‍♂️
Sep 19, 2023, 9:38 PM
I knew it was something obvious. Thanks for the help
Sep 19, 2023, 9:38 PM
You’re very welcome!
Sep 19, 2023, 9:40 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?

Categorized in