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

posts.tsx

40 lines983 Bytes

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})