Using arrays in Groq queries with Next.js and Sanity.io

19 replies
Last updated: Jun 7, 2022
hello guys, I would love to have ur opinion on an issue i am having
let's say I have an array of strings,
const str = ['male', 'female']
i have a field in sanity called
gender
which is a string containing the gender i want to put it to the query to check
gender in [...str]
,
how can i achieve it in
groq
?
AI Update

Hey! Great question about using arrays in GROQ queries.

To check if a gender field matches any value in your array of strings, you can use the in operator in GROQ. Here's how:

*[gender in ["male", "female"]]

How it works: The in operator checks if the left-hand value (your gender field) matches any element in the right-hand array. It compares for equality with each element and returns true as soon as it finds a match.

Important note about variables: GROQ doesn't support JavaScript variables directly in queries. If you have a JavaScript array like const str = ['male', 'female'], you'll need to construct the query string dynamically:

const str = ['male', 'female'];
const query = `*[gender in ${JSON.stringify(str)}]`;

This constructs: *[gender in ["male","female"]]

More examples:

// Basic usage
*[gender in ["male", "female"]]

// Combined with other filters
*[_type == "person" && gender in ["male", "female"]]

// With projection
*[gender in ["male", "female"]] {
  name,
  gender,
  age
}

For the opposite (NOT in): If you want to find documents where gender is NOT in your array:

*[!(gender in ["male", "female"])]

The in operator is really handy for this kind of filtering - it's much cleaner than chaining multiple OR conditions!

You can pass an array as argument to your query and then use it like this:
gender in $genders

client.fetch(
  query,
  { genders: [ 'male', 'female' ] }
)
(Also consider this your friendly reminder that there are more genders than “man” and “woman”. 😉)
absolutely, absolutelyi just put it there for a quick example. But will be more careful from now.
Thank u
i did not used the
client.fetch
, so i figured out a way, let me know what do u think
*[_type == "doctor" && gender in ${JSON.stringify(
          selectedGendersAndLanguages.map((item) => item.toLocaleLowerCase()),
        )}]
That works, but passing strings directly to the query itself is not recommended. What do you use to communicate with Sanity? The REST API?
i used the
next-saniy
package and
react-query
to handle the query and fetching
With
usePreviewSubscription
, right?
i used this way, did not use
usePreviewSubscription

import { createClient } from 'next-sanity'

export const SanityCDNReadClient = createClient(config).withConfig({
  useCdn: false,
})
That’s your client though, not the way you use it to query data. 🙂
I assume you do
SanityCDNReadClient.fetch(…)
somewhere?
sorry i missed the most important part, i use a package called
next-sanity-extra
for setting up sanity, fetching static props, and using live previews
import { setupNextSanity } from 'next-sanity-extra'
export const { sanityClient, imageUrlBuilder, PortableText, sanityStaticProps, useSanityQuery } =
  setupNextSanity(config)
sorry
user F
, i got it, my explanation was pretty bad, i am using the
client.fetch
in my code, but i completely forgot about it as i am using react-query for handling states, but forgot i seatup a client.fetch,
sorry for confusing u so much and wasting ur time a bit
Ah, no worries. So you can pass a second parameter to the fetch method, which is an object of parameters. These parameters can then be referenced in your query string. 🙂
got it,thank u so much, for ur help & guidence
Cheers! 💚

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?