I want to add a view with the Structure builder (S.view.component) where I list similar documents based on the title. What would be the best way to use GROQ there?
For creating a custom view with S.view.component() that displays similar documents based on title, you have a couple of good options for querying data with GROQ:
Using useClient Hook (Recommended)
The easiest approach is to use the useClient hook from the sanity package. This hook provides a configured Sanity client that's ready to use in your component:
import { useClient } from 'sanity'
import { useEffect, useState } from 'react'
function SimilarDocumentsView(props) {
const client = useClient({apiVersion: '2024-01-01'})
const [similarDocs, setSimilarDocs] = useState([])
const { documentId, document } = props
useEffect(() => {
if (!document?.title) return
const query = `*[_type == $type && _id != $id && title match $title][0...5] {
_id,
title,
_type
}`
client.fetch(query, {
type: document._type,
id: documentId,
title: `${document.title}*`
}).then(setSimilarDocs)
}, [client, documentId, document?.title])
return (
<div>
<h2>Similar Documents</h2>
{similarDocs.map(doc => (
<div key={doc._id}>{doc.title}</div>
))}
</div>
)
}The useClient hook is simpler than working with documentStore directly and gives you a fully configured client for making GROQ queries.
Alternative: Using documentStore
While you could use the documentStore from the Studio's context, it's generally more complex and intended for lower-level document operations. The useClient hook abstracts away that complexity and is the recommended approach for custom views.
Props Available in Custom Views
Your custom view component receives useful props including:
documentId- The ID of the current documentdocument- The current document's data (including draft changes)schemaType- The schema type definition
Structure Builder Setup
In your Structure Builder configuration:
S.view
.component(SimilarDocumentsView)
.title('Similar Documents')The useClient approach is cleaner, more maintainable, and follows current Sanity Studio v3 best practices for custom document views.
Show original thread7 replies
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.