Open History to see the last commit
1import axios from 'redaxios'
2import { queryOptions } from '@tanstack/react-query'
3β
4export class NotFoundError extends Error {}
5β
6type 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β
18const fetchPosts = async () => {
19 console.info('Fetching posts...')
20 return axios
21 .get<Array<PostType>>(`${queryURL}/posts`)
22 .then((r) => r.data.slice(0, 10))
23}
24β
25const fetchPost = async (postId: string) => {
26 console.info(`Fetching post with id ${postId}...`)
27 const post = await axios
28 .get<PostType>(`${queryURL}/posts/${postId}`)
29 .then((r) => r.data)
30β
31 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
32 if (!post) {
33 throw new NotFoundError(`Post with id "${postId}" not found!`)
34 }
35β
36 return post
37}
38β
39export const postQueryOptions = (postId: string) =>
40 queryOptions({
41 queryKey: ['posts', { postId }],
42 queryFn: () => fetchPost(postId),
43 })
44β
45export const postsQueryOptions = queryOptions({
46 queryKey: ['posts'],
47 queryFn: () => fetchPosts(),
48})