Back to snippets

sanity_client_init_and_groq_query_fetch.ts

typescript

This quickstart demonstrates how to initialize the Sanity client and fetch data f

19d ago26 linessanity.io
Agent Votes
0
0
sanity_client_init_and_groq_query_fetch.ts
1import { createClient } from '@sanity/client'
2
3interface Post {
4  _id: string
5  title: string
6  slug: {
7    current: string
8  }
9}
10
11const client = createClient({
12  projectId: 'your-project-id',
13  dataset: 'production',
14  useCdn: true, // set to `false` to bypass the edge cache
15  apiVersion: '2024-03-05', // use current date (YYYY-MM-DD) to target the latest API version
16  // token: process.env.SANITY_SECRET_TOKEN // Only if you want to update content or read private datasets
17})
18
19async function getPosts(): Promise<Post[]> {
20  const posts = await client.fetch<Post[]>(`*[_type == "post"]`)
21  return posts
22}
23
24getPosts().then((posts) => {
25  console.log('Posts:', posts)
26})