Can you run GROQ inside a Document Preview?
Unfortunately, you cannot run GROQ queries directly inside the prepare function of a preview configuration. The prepare function is synchronous and doesn't have access to the Sanity client or the ability to make additional queries. This is a known limitation mentioned in the Sanity documentation.
However, you have a couple of alternatives to achieve what you're trying to do:
Option 1: Use a Custom Preview Component (Recommended)
You can create a custom preview component that can use the Sanity client to fetch additional data:
import { PreviewProps } from 'sanity'
import { useClient } from 'sanity'
import { useEffect, useState } from 'react'
const CustomReferencePreview = (props: PreviewProps) => {
const client = useClient({ apiVersion: '2024-01-01' })
const [hasBackReference, setHasBackReference] = useState(false)
const documentId = props.documentId
const parentId = /* you'll need to pass this somehow */
useEffect(() => {
const checkBackReference = async () => {
const result = await client.fetch(
`*[_id == $documentId && references($parentId)][0]`,
{ documentId, parentId }
)
setHasBackReference(!!result)
}
checkBackReference()
}, [documentId, parentId, client])
return props.renderDefault({
...props,
subtitle: hasBackReference ? 'βοΈ Mutual reference' : props.subtitle
})
}
// In your schema
{
name: 'myReference',
type: 'reference',
components: {
preview: CustomReferencePreview
}
}Option 2: Pre-compute the Flag with Sanity Functions
If this relationship is important, consider adding a field that gets updated when the relationship changes. You could use Sanity Functions with a document mutation event handler to automatically update this flag whenever documents are linked:
// In sanity.blueprint.ts
export default defineBlueprint({
functions: [
{
name: 'update-mutual-references',
handler: './functions/updateMutualReferences.ts',
on: {
mutation: {
documentTypes: ['yourDocumentType']
}
}
}
]
})Option 3: Select from a Computed Field
If you add a computed field to your document that tracks mutual references, you can select it in your preview:
preview: {
select: {
title: 'title',
hasMutualReference: 'mutualReferenceFlag' // pre-computed field
},
prepare({ title, hasMutualReference }) {
return {
title,
subtitle: hasMutualReference ? 'βοΈ Mutual' : 'One-way β'
}
}
}The custom preview component (Option 1) is probably your best bet for dynamic checking, though be aware it will make queries for each preview rendered, which could impact performance with many items. The Sanity Functions approach (Option 2) would be more performant as it pre-computes the relationship, but requires more setup.
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.