😎 Discover cool tips and tricks for customization in our next Developer Deep Dive virtual event - sign up now!

Reusable GROQ query strings in Next.js app

8 replies
Last updated: Feb 22, 2023
I am wondering if there are any patterns y’all like for “reusable GROQ query strings”… currently I am calling this query (or one very similar) in about 3 different places in my nextjs app.
Feb 21, 2023, 11:21 PM

*[_type == "blogPost" && slug.current == "${blogPostSlug}"]{
    _id,
    title,
    author->{
      name,
      slug{ current },
      bio,
      authorImage{ asset->{path, url} }
    },
    body[]{
      _type == 'blogImageRef' => @->{
        caption,
        image{
          asset->
        },
        imageTags
      },
      _type == 'imageCollectionRef' => @->{
        _id,
        collectionName,
        collectionImages[]->,
      },
      _type != 'reference' => @,
    },
    categories[]->{ title, description, slug{ current } },
    excerpt,
    location->{ locationName, mapLocation },
    mainImage->{_createdAt, caption, image{ asset->{ path, url } }, author->{ name, slug } },
    publishedAt,
    slug{ current },
my thinking here is to turn the subcomponents of this query into reusable strings… something like

author->{
      name,
      slug{ current },
      bio,
      authorImage{ asset->{path, url} }
    }
gets turned into

${unpackAuthorRef}

Feb 21, 2023, 11:23 PM
Or if there is already a solution for some pattern that works for this
Feb 21, 2023, 11:23 PM
thank you!
Feb 21, 2023, 11:23 PM
The Hydrogen-Sanity-Demo has some great fragments to look through. Here’s the PortableText GROQ as an example

https://github.com/sanity-io/hydrogen-sanity-demo/blob/main/src/fragments/sanity/portableText/portableText.ts
Feb 22, 2023, 12:33 AM
Friendly heads up. The code of conduct for the community requests not calling the group Guys.

https://www.sanity.io/docs/community-code-of-conduct#c6090fc307bc

“This includes memes, emojis, and GIFs. And remember, we’re not only “guys” – including us at Sanity HQ – (we are people, folks, friends, y’all, etc).”
Feb 22, 2023, 12:37 AM
Ooops I am so sorry!
Feb 22, 2023, 1:58 AM
Thanks for ^^ linking hydrogen example! Glad to see I was on the right track somewhat
Feb 22, 2023, 2:02 AM
Very welcome!
Feb 22, 2023, 2:36 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?