How to fetch reference field details in Sanity preview.prepare?
You can access reference fields in your preview.prepare by using dot notation in the select object! Here's how to fix your code:
preview: {
select: {
productName: 'productRef.name' // Use dot notation to dereference
},
prepare(selection) {
const { productName } = selection
return {
title: 'Product',
subtitle: productName // This will now have the actual name
}
}
}The key is that you need to specify the path through the reference in the select object using dot notation (productRef.name). The prepare function itself can't dereference or make queries - it only works with what you've selected.
You can also access multiple fields from the reference:
preview: {
select: {
productName: 'productRef.name',
productPrice: 'productRef.price',
productImage: 'productRef.image'
},
prepare({ productName, productPrice, productImage }) {
return {
title: productName,
subtitle: `$${productPrice}`,
media: productImage
}
}
}This works for references at any depth, and you can even access array items using numeric indices like productRef.images.0 for the first image in an array.
The preview configuration documentation has more details on all the ways you can customize how your content appears in Studio!
Show original thread1 reply
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.