Options including the document handle properties (documentId
, documentType
, etc.) and the projection
.
The projected data, typed based on Typegen.
// ProjectionComponent.tsx
import {useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'
import {useRef} from 'react'
import {defineProjection} from 'groq'
// Define props using DocumentHandle with the specific document type
type ProjectionComponentProps = {
doc: DocumentHandle<'book'> // Typegen knows 'book'
}
// This is required for typegen to generate the correct return type
const myProjection = defineProjection(`{
title,
'coverImage': cover.asset->url,
'authors': array::join(authors[]->{'name': firstName + ' ' + lastName}.name, ', ')
}`)
export default function ProjectionComponent({ doc }: ProjectionComponentProps) {
const ref = useRef(null) // Optional ref to track viewport intersection for lazy loading
// Spread the doc handle into the options
// Typegen infers the return type based on 'book' and the projection
const { data } = useDocumentProjection({
...doc, // Pass the handle properties
ref,
projection: myProjection,
})
// Suspense handles initial load, check for data existence after
return (
<article ref={ref}>
<h2>{data.title ?? 'Untitled'}</h2>
{data.coverImage && <img src={data.coverImage} alt={data.title} />}
<p>{data.authors ?? 'Unknown authors'}</p>
</article>
)
}
// Usage:
// import {createDocumentHandle} from '@sanity/sdk-react'
// const myDocHandle = createDocumentHandle({ documentId: 'book123', documentType: 'book' })
// <Suspense fallback='Loading preview...'>
// <ProjectionComponent doc={myDocHandle} />
// </Suspense>
Fetch a projection with an explicitly defined return type TData
.
Options including the document handle properties (documentId
, etc.) and the projection
.
The projected data, cast to the explicit type TData
.
import {useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'
import {useRef} from 'react'
interface SimpleBookPreview {
title?: string;
authorName?: string;
}
type BookPreviewProps = {
doc: DocumentHandle
}
function BookPreview({ doc }: BookPreviewProps) {
const ref = useRef(null)
const { data } = useDocumentProjection<SimpleBookPreview>({
...doc,
ref,
projection: `{ title, 'authorName': author->name }`
})
return (
<div ref={ref}>
<h3>{data.title ?? 'No Title'}</h3>
<p>By: {data.authorName ?? 'Unknown'}</p>
</div>
)
}
// Usage:
// import {createDocumentHandle} from '@sanity/sdk-react'
// const doc = createDocumentHandle({ documentId: 'abc', documentType: 'book' })
// <Suspense fallback='Loading...'>
// <BookPreview doc={doc} />
// </Suspense>
Fetch a projection, relying on Typegen for the return type based on the handle and projection.