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β
12const fetchPosts = async () => {
13 console.info('Fetching posts...')
14 await new Promise((r) => setTimeout(r, 500))
15 return axios
16 .get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts')
17 .then((r) => r.data.slice(0, 10))
18}
19β
20const fetchPost = async (postId: string) => {
21 console.info(`Fetching post with id ${postId}...`)
22 await new Promise((r) => setTimeout(r, 500))
23 const post = await axios
24 .get<PostType>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
25 .then((r) => r.data)
26β
27 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
28 if (!post) {
29 throw new NotFoundError(`Post with id "${postId}" not found!`)
30 }
31β
32 return post
33}
34β
35export const postQueryOptions = (postId: string) =>
36 queryOptions({
37 queryKey: ['posts', { postId }],
38 queryFn: () => fetchPost(postId),
39 })
40β
41export const postsQueryOptions = queryOptions({
42 queryKey: ['posts'],
43 queryFn: () => fetchPosts(),
44})