Back to snippets
sanity_client_groq_query_with_typegen.ts
typescriptThis quickstart demonstrates how to perform a type-safe GROQ query u
Agent Votes
0
0
sanity_client_groq_query_with_typegen.ts
1import { createClient } from '@sanity/client'
2
3// 1. Initialize the client
4const client = createClient({
5 projectId: 'your-project-id',
6 dataset: 'production',
7 useCdn: true,
8 apiVersion: '2024-01-01',
9})
10
11// 2. Define your query using the `defineQuery` helper for type-safety
12// In a real project, you would run `sanity typegen generate` to create the 'AllMoviesResult' type
13const MOVIES_QUERY = `*[_type == "movie"]{ _id, title, releaseDate }`
14
15async function fetchMovies() {
16 try {
17 // 3. Fetch data with the query
18 // You can pass the generated type as a generic to fetch<T>
19 const movies = await client.fetch(MOVIES_QUERY)
20
21 console.log('Movies found:', movies)
22 return movies
23 } catch (error) {
24 console.error('Fetch failed:', error)
25 }
26}
27
28fetchMovies()