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

posts.ts

44 lines1.0 KB

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