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

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
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
Jun 7, 2022, 7:13 AM
You can pass an array as argument to your query and then use it like this:
gender in $genders

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

import { createClient } from 'next-sanity'

export const SanityCDNReadClient = createClient(config).withConfig({
  useCdn: false,
Jun 7, 2022, 8:00 AM
That’s your client though, not the way you use it to query data. 🙂
Jun 7, 2022, 8:00 AM
I assume you do
Jun 7, 2022, 8:01 AM
sorry i missed the most important part, i use a package called
for setting up sanity, fetching static props, and using live previews
Jun 7, 2022, 8:06 AM
import { setupNextSanity } from 'next-sanity-extra'
export const { sanityClient, imageUrlBuilder, PortableText, sanityStaticProps, useSanityQuery } =
Jun 7, 2022, 8:07 AM
user F
, i got it, my explanation was pretty bad, i am using the
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,
Jun 7, 2022, 8:12 AM
sorry for confusing u so much and wasting ur time a bit
Jun 7, 2022, 8:12 AM
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. 🙂
Jun 7, 2022, 8:13 AM
Jun 7, 2022, 8:13 AM
got it,thank u so much, for ur help & guidence
Jun 7, 2022, 8:15 AM
Cheers! 💚
Jun 7, 2022, 8:15 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?