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

posts.ts

44 lines1.1 KB

1import axios from 'redaxios'
2import { queryOptions } from '@tanstack/solid-query'
3​
4export class NotFoundError extends Error {}
5​
6type PostType = {
7 id: string
8 title: string
9 body: string
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))
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
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})