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

posts.tsx

36 lines935 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​
11export const fetchPost = createServerFn({ method: 'GET' })
12 .validator((d: string) => d)
13 .handler(async ({ data }) => {
14 console.info(`Fetching post with id ${data}...`)
15 const post = await axios
16 .get<PostType>(`https://jsonplaceholder.typicode.com/posts/${data}`)
17 .then((r) => r.data)
18 .catch((err) => {
19 console.error(err)
20 if (err.status === 404) {
21 throw notFound()
22 }
23 throw err
24 })
25​
26 return post
27 })
28​
29export const fetchPosts = createServerFn({
30 method: 'GET',
31}).handler(async () => {
32 console.info('Fetching posts...')
33 return axios
34 .get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts')
35 .then((r) => r.data.slice(0, 10))
36})