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 queryURL = 'https://jsonplaceholder.typicode.com'
13β
14const fetchPosts = async () => {
15 console.info('Fetching posts...')
16 return axios
17 .get<Array<PostType>>(`${queryURL}/posts`)
18 .then((r) => r.data.slice(0, 10))
19}
20β
21const fetchPost = async (postId: string) => {
22 console.info(`Fetching post with id ${postId}...`)
23 const post = await axios
24 .get<PostType>(`${queryURL}/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})