Configuration options for the infinite list
An object containing the list of document handles, the loading state, the total count of retrieved document handles, and a function to load more
import {
useDocuments,
createDatasetHandle,
type DatasetHandle,
type DocumentHandle,
type SortOrderingItem
} from '@sanity/sdk-react'
import {Suspense} from 'react'
// Define a component to display a single document (using useDocumentProjection for efficiency)
function MyDocumentComponent({doc}: {doc: DocumentHandle}) {
const {data} = useDocumentProjection<{title?: string}>({
...doc, // Pass the full handle
projection: '{title}'
})
return <>{data?.title || 'Untitled'}</>
}
// Define props for the list component
interface DocumentListProps {
dataset: DatasetHandle
documentType: string
search?: string
}
function DocumentList({dataset, documentType, search}: DocumentListProps) {
const { data, hasMore, isPending, loadMore, count } = useDocuments({
...dataset,
documentType,
search,
batchSize: 10,
orderings: [{field: '_createdAt', direction: 'desc'}],
})
return (
<div>
<p>Total documents: {count}</p>
<ol>
{data.map((docHandle) => (
<li key={docHandle.documentId}>
<Suspense fallback="Loading…">
<MyDocumentComponent docHandle={docHandle} />
</Suspense>
</li>
))}
</ol>
{hasMore && (
<button onClick={loadMore}>
{isPending ? 'Loading...' : 'Load More'}
</button>
)}
</div>
)
}
// Usage:
// const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })
// <DocumentList dataset={myDatasetHandle} documentType="post" search="Sanity" />
import {useState} from 'react'
import {useDocuments} from '@sanity/sdk-react'
export default function FilteredAuthors() {
const [max, setMax] = useState(2)
const {data} = useDocuments({
documentType: 'author',
filter: 'length(books) <= $max',
params: {max},
})
return (
<>
<input
id="maxBooks"
type="number"
value={max}
onChange={e => setMax(e.currentTarget.value)}
/>
{data.map(author => (
<Suspense key={author.documentId}>
<MyAuthorComponent documentHandle={author} />
</Suspense>
))}
</>
)
}
Retrieves batches of DocumentHandles, narrowed by optional filters, text searches, and custom ordering, with infinite scrolling support. The number of document handles returned per batch is customizable, and additional batches can be loaded using the supplied
loadMore
function.