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:
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!
🚀
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 }), }; }, },
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:
Or maybe (I don’t know your schema):
theme: 'cards.0.theme.hex'
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:
Or maybe (I don’t know your schema):
theme: 'cards.0.theme.hex'
theme: 'cards.0.hex'
Feb 8, 2025, 7:47 PM
theme: 'cards.0.theme.hexworked ✨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`:
And then managing those in your
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
preparefunction.
Feb 8, 2025, 8:42 PM
C
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.