🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Using a given parameter as a where condition in GROQ in Sanity.io

2 replies
Last updated: Dec 12, 2023
Hey, any way to set a given param as a where condition in GROQ?
Like if I generate a very complex condition outside the query, because I need multiple other resources to get the wanted paramters and values from another api endpoint, simplified, something like this :


 const queryParams = {
    //...
    superComplexCondition: `(.... && .... && (... || ...))`,
  }

  const products = await sanityFetch<ProductsQueryResponseType>({
    query: productsQuery,
    params: {
      ...queryParams,
      language: 'en',
    },
    cache: 'no-store',
  })

groq`
*[_type == "product" && $superComplexCondition]{
  _id,
  title
}
Maybe, there's a trick?
🙂
Thank you!
Dec 12, 2023, 8:34 AM
The only way would be to use template literals:

groq`
*[_type == "product" && ${superComplexCondition}]{
  _id,
  title
}
Dec 12, 2023, 9:44 AM
Ok thank you
Dec 12, 2023, 9:44 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?