Open History to see the last commit
1import { notFound } from '@tanstack/react-router'
2import { createServerFn } from '@tanstack/react-start'
3β
4export type PostType = {
5 id: string
6 title: string
7 body: string
8}
9β
10export const fetchPost = createServerFn({ method: 'POST' })
11 .inputValidator((d: string) => d)
12 .handler(async ({ data, context }) => {
13 console.log('Request context:', context)
14 console.info(`Fetching post with id ${data}...`)
15 const res = await fetch(
16 `https://jsonplaceholder.typicode.com/posts/${data}`,
17 )
18 if (!res.ok) {
19 if (res.status === 404) {
20 throw notFound()
21 }
22β
23 throw new Error('Failed to fetch post')
24 }
25β
26 const post = (await res.json()) as PostType
27β
28 return post
29 })
30β
31export const fetchPosts = createServerFn().handler(async () => {
32 console.info('Fetching posts...')
33 const res = await fetch('https://jsonplaceholder.typicode.com/posts')
34 if (!res.ok) {
35 throw new Error('Failed to fetch posts')
36 }
37β
38 const posts = (await res.json()) as Array<PostType>
39β
40 return posts.slice(0, 10)
41})