🎤 Builder Talk: The Story Behind Lady Gaga’s Digital Experience – Register now

Handling nested references in Sanity preview function

6 replies
Last updated: Feb 8, 2025
Hey everyone! 👋
I’m trying to get a nested array of referenced objects inside the preview function, but I’m running into some issues. My schema looks something like this:


preview: {
  select: {
    cards: 'cards',
    theme: 'cards[].theme.hex',
  },
  prepare({ cards, theme }) {
    return {
      title: 'Dual',
      subtitle: 'Dual Block',
      media: withCustomParams(DualMedia, { cards }),
    };
  },
},
The cards array contains references to another document type, and each referenced document has a theme.hex field. However, I’m not sure how to correctly select the nested theme values from these referenced objects.

I’ve checked the
Sanity docs on previews , but it only covers direct references, not arrays of references.
Is there a recommended way to handle this in select? Or do I need to resolve the references manually in prepare?

Thanks in advance!
🚀
Feb 8, 2025, 7:45 PM
Preview use a weird syntax that doesn’t translate to GROQ in some cases. Notably, you won’t use square brackets and I think you can treat them as if they’re dereferenced. Can you try changing theme (in your select) to:

theme: 'cards.0.theme.hex'
Or maybe (I don’t know your schema):


theme: 'cards.0.hex'
Feb 8, 2025, 7:47 PM
Previews use a weird syntax that doesn’t translate to GROQ in some cases. Notably, you won’t use square brackets and I think you can treat them as if they’re dereferenced. Can you try changing theme (in your select) to:

theme: 'cards.0.theme.hex'
Or maybe (I don’t know your schema):


theme: 'cards.0.hex'
Feb 8, 2025, 7:47 PM
theme: 'cards.0.theme.hex
worked ✨Is it possible to get all array items of cards?
Feb 8, 2025, 8:28 PM
Great!
Unfortunately, no. You’d need to request them individually, getting as many as you need in the `select`:


theme0: 'cards.0.theme.hex
theme1: 'cards.1.theme.hex
theme2: 'cards.2.theme.hex
theme3: 'cards.3.theme.hex
And then managing those in your
prepare
function.
Feb 8, 2025, 8:42 PM
Ok, I see. Thanks for the quick answer
Feb 8, 2025, 8:48 PM
Once you do them manually like that, the main 'cards' should contain them all. Weird quirk. I've dug into the sanity logic a few times trying to 'fix' this and it is annoying but I haven't solved it yet.
Feb 8, 2025, 9:16 PM

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?