Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

posts.tsx

41 lines1.0 KB

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 .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()
27​
28 return post as PostType
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()
39​
40 return (posts as Array<PostType>).slice(0, 10)
41})