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