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: number
6 title: string
7 body: string
8}
9β
10export const fetchPost = createServerFn({ method: 'POST' })
11 .validator((d: string) => d)
12 .handler(async ({ data }) => {
13 console.info(`Fetching post with id ${data}...`)
14 const res = await fetch(
15 `https://jsonplaceholder.typicode.com/posts/${data}`,
16 )
17 if (!res.ok) {
18 if (res.status === 404) {
19 throw notFound()
20 }
21β
22 throw new Error('Failed to fetch post')
23 }
24β
25 const post = await res.json()
26β
27 return post as PostType
28 })
29β
30export const fetchPosts = createServerFn().handler(async () => {
31 console.info('Fetching posts...')
32 const res = await fetch('https://jsonplaceholder.typicode.com/posts')
33 if (!res.ok) {
34 throw new Error('Failed to fetch posts')
35 }
36β
37 const posts = await res.json()
38β
39 return (posts as Array<PostType>).slice(0, 10)
40})