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β
12let queryURL = 'https://jsonplaceholder.typicode.com'
13β
14if (import.meta.env.VITE_NODE_ENV === 'test') {
15 queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}`
16}
17β
18export const fetchPosts = createServerFn({ method: 'GET' }).handler(
19 async () => {
20 console.info('Fetching posts...')
21 return axios
22 .get<Array<PostType>>(`${queryURL}/posts`)
23 .then((r) => r.data.slice(0, 10))
24 },
25)
26β
27export const postsQueryOptions = () =>
28 queryOptions({
29 queryKey: ['posts'],
30 queryFn: () => fetchPosts(),
31 })
32β
33export const fetchPost = createServerFn({ method: 'GET' })
34 .inputValidator((postId: string) => postId)
35 .handler(async ({ data: postId }) => {
36 console.info(`Fetching post with id ${postId}...`)
37 const post = await axios
38 .get<PostType>(`${queryURL}/posts/${postId}`)
39 .then((r) => r.data)
40 .catch((err) => {
41 console.error(err)
42 if (err.status === 404) {
43 throw notFound()
44 }
45 throw err
46 })
47β
48 return post
49 })
50β
51export const postQueryOptions = (postId: string) =>
52 queryOptions({
53 queryKey: ['post', postId],
54 queryFn: () => fetchPost({ data: postId }),
55 })