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

posts.tsx

38 lines976 Bytes

1import { notFound } from '@tanstack/solid-router'
2import { createServerFn } from '@tanstack/solid-start'
3import axios from 'redaxios'
4​
5export type PostType = {
6 id: string
7 title: string
8 body: string
9}
10​
11const queryURL = 'https://jsonplaceholder.typicode.com'
12​
13export const fetchPost = createServerFn({ method: 'GET' })
14 .validator((postId: string) => postId)
15 .handler(async ({ data: postId }) => {
16 console.info(`Fetching post with id ${postId}...`)
17 const post = await axios
18 .get<PostType>(`${queryURL}/posts/${postId}`)
19 .then((r) => r.data)
20 .catch((err) => {
21 console.error(err)
22 if (err.status === 404) {
23 throw notFound()
24 }
25 throw err
26 })
27​
28 return post
29 })
30​
31export const fetchPosts = createServerFn({ method: 'GET' }).handler(
32 async () => {
33 console.info('Fetching posts...')
34 return axios
35 .get<Array<PostType>>(`${queryURL}/posts`)
36 .then((r) => r.data.slice(0, 10))
37 },