Filtering a reference field in GROQ and using the `sanity-micro-client` package for live preview in Next.js.

19 replies
Last updated: May 18, 2022
Morning! Quick question:
Is it possible to filter a reference field in GROQ?


*[_type == "post" && category->slug == "methods"]

Trying to do something like ^ where
category
is a reference in
post
and I’m trying to match the slug 🤔
May 18, 2022, 1:30 PM
Yes, that works.
May 18, 2022, 1:31 PM
If your
slug
field on the
category
reference is a
slug
type, you need to do
category->slug.current
.
May 18, 2022, 1:31 PM
Ahahaha thanks, that was close 😄
May 18, 2022, 1:32 PM
btw
user F
I checked out your `sanity-micro-client`package but I don’t think it’s on npm
May 18, 2022, 1:33 PM
was trying to get live preview on Next.js the other day
May 18, 2022, 1:33 PM
Yes, I haven’t published it because I wasn’t sure anyone would be interested. 😅
May 18, 2022, 1:36 PM
Ah I found it while searching through Slack here lol
May 18, 2022, 1:37 PM
If you want to use it, I can publish it for you.
May 18, 2022, 1:41 PM
Happy to. 🙂
May 18, 2022, 1:41 PM
Are you using it a lot in your projects? I was intrigued by the idea of not adding client code like
next-sanity
, but as a noob I’m not yet sure what the limitations of this wrapper is. For example I see the query conditions being stitched with
&&
, which seems like it restricts other types of queries
May 18, 2022, 1:47 PM
I took a look at the source code and was thinking of using a less opinionated version of it, since you did add some helpful utils around drafts
May 18, 2022, 1:48 PM
I’m using it in all my Sanity projects, yes. 🙂
May 18, 2022, 1:50 PM
What I like about the conditions stitching is it makes queries very obvious, especially when you start having a lot of conditions.
conditions: [
  '_type == "post"',
  'category -> slug.current == $category',
  'defined(body)'
]
May 18, 2022, 1:50 PM
And you can still use `||`:
conditions: [
  '_type == "post"',
  '(category -> slug.current == $category || !defined(category))',
]
May 18, 2022, 1:52 PM
I’m not pushing you to use it though, you do you. 😄 You can also copy and paste the code or something.
May 18, 2022, 1:52 PM
Ah, for long queries I’ve setup Prettier so it formats, and Groq highlighting in VScode (which requires `groq``` strings)
May 18, 2022, 1:55 PM
I will prob end up copy pasting 😛
May 18, 2022, 1:55 PM
thanks for offering to publish it tho
May 18, 2022, 1:56 PM
Ah yes, I see. I’m personally not a fan of super huge query strings like that. I do like that my helper breaks it in sensible parts (the conditions, the fields, the order, the slicing, etc.). 🙂
May 18, 2022, 1:57 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?