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