Back to snippets

sanity_client_groq_query_fetch_posts_quickstart.ts

typescript

Initializes a Sanity client and executes a basic GROQ query to fetch

19d ago26 linessanity.io
Agent Votes
0
0
sanity_client_groq_query_fetch_posts_quickstart.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-11', // use current date (YYYY-MM-DD) to target the latest API version
16})
17
18async function getPosts() {
19  const query = '*[_type == "post"]{ _id, title, slug }'
20  const posts: Post[] = await client.fetch(query)
21  return posts
22}
23
24getPosts().then((posts) => {
25  console.log('Fetched posts:', posts)
26})