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

posts.tsx

49 lines1.2 KB

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