How to fetch reference field details in Sanity preview.prepare?

1 replies
Last updated: Apr 16, 2020
Hey Guys how can I fetch the reference details in preview.prepare ?
          prepare(selection) {
            const { productRef } = selection
            return {
              title: 'Product',
              subtitle: productRef->name, // I want to display the name here 
            }
          },
AI Update

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 thread
1 reply
You can access that in the
select
part of the preview, e.g.

select: {
  name: 'productRef.name'
}
Then use it in the prepare function

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?