Executes a GROQ query, inferring the result type from the query string and options. Leverages Sanity Typegen if configured for enhanced type safety.
Configuration for the query, including query
, optional params
, projectId
, dataset
, etc.
An object containing data
(typed based on the query) and isPending
(for transitions).
The query result, typed based on the GROQ query string
True if a query transition is in progress
import {useQuery} from '@sanity/sdk-react'
import {defineQuery} from 'groq'
const myQuery = defineQuery(`*[_type == "movie"]{_id, title}`)
function MovieList() {
// Typegen infers the return type for data
const {data} = useQuery({ query: myQuery })
return (
<div>
<h2>Movies</h2>
<ul>
{data.map(movie => <li key={movie._id}>{movie.title}</li>)}
</ul>
</div>
)
}
// Suspense boundary should wrap <MovieList /> for initial load
import {useQuery} from '@sanity/sdk-react'
import {defineQuery} from 'groq'
const myQuery = defineQuery(`*[_type == "movie" && _id == $id][0]`)
function MovieDetails({movieId}: {movieId: string}) {
// Typegen infers the return type based on query and params
const {data, isPending} = useQuery({
query: myQuery,
params: { id: movieId }
})
return (
// utilize `isPending` to signal to users that new data is coming in
// (e.g. the `movieId` changed and we're loading in the new one)
<div style={{ opacity: isPending ? 0.5 : 1 }}>
{data ? <h1>{data.title}</h1> : <p>Movie not found</p>}
</div>
)
}
Executes a GROQ query with an explicitly provided result type TData
.
Configuration for the query, including query
, optional params
, projectId
, dataset
, etc.
An object containing data
(cast to TData
) and isPending
(indicates whether a query resolution is pending; note that Suspense handles initial loading states). *
The query result, cast to the provided type TData
True if another query is resolving in the background (suspense handles the initial loading state)
import {useQuery} from '@sanity/sdk-react'
interface CustomMovieTitle {
movieTitle?: string
}
function FirstMovieTitle() {
// Provide the explicit type TData
const {data, isPending} = useQuery<CustomMovieTitle>({
query: '*[_type == "movie"][0]{ "movieTitle": title }'
})
return (
<h1 style={{ opacity: isPending ? 0.5 : 1 }}>
{data?.movieTitle ?? 'No title found'}
</h1>
)
}
Fetches data and subscribes to real-time updates using a GROQ query.
Remarks
This hook provides a convenient way to fetch data from your Sanity dataset and automatically receive updates in real-time when the queried data changes.
Features:
isPending
).TData
for the query result.