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

posts.tsx

55 lines1.4 KB

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
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}`
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 },
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 })