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

post-viewer.tsx

93 lines2.5 KB

1import { useQuery } from '@tanstack/solid-query'
2import { For, createSignal, resetErrorBoundaries, untrack } from 'solid-js'
3import { Example } from './example'
4import { QueryBoundary } from './query-boundary'
5import type { Component } from 'solid-js'
6import { postsQueries } from '~/services/posts/queries'
7​
8export interface PostViewerProps {
9 deferStream?: boolean
10 sleep?: number
11 simulateError?: boolean
13​
14export const PostViewer: Component<PostViewerProps> = (props) => {
15 const [simulateError, setSimulateError] = createSignal(
16 untrack(() => props.simulateError),
17 )
18 const [postId, setPostId] = createSignal(1)
19​
20 const shouldSimulateError = () =>
21 simulateError() || (simulateError() !== false && postId() === 5)
22​
23 const query = useQuery(() => ({
24 ...postsQueries.detail({
25 postId: postId(),
26 sleep: props.sleep,
27 simulateError: shouldSimulateError(),
28 }),
29 deferStream: props.deferStream,
30 throwOnError: true,
31 }))
32​
33 return (
34 <Example
35 title="Post Query"
36 deferStream={props.deferStream}
37 sleep={props.sleep}
38 >
39 <div style={{ 'margin-top': '20px' }}>
40 <button
41 onClick={() => {
42 setPostId(Math.max(postId() - 1, 1))
43 resetErrorBoundaries()
44 }}
45 >
46 Previous Post
47 </button>
48 <button
49 onClick={() => {
50 setPostId(Math.min(postId() + 1, 100))
51 resetErrorBoundaries()
52 }}
53 >
54 Next Post
55 </button>
56 </div>
57​
58 {/* NOTE: without this extra wrapping div, for some reason solid ends up printing two errors... feels like a bug in solid. */}
59 <div>
60 <QueryBoundary
61 query={query}
62 loadingFallback={<div class="loader">loading post...</div>}
63 errorFallback={(err, retry) => (
64 <div>
65 <div class="error">{err.message}</div>
66 <button
67 onClick={() => {
68 setSimulateError(false)
69 retry()
70 }}
71 >
72 retry
73 </button>
74 </div>
75 )}
76 >
77 {(posts) => (
78 <For each={posts}>
79 {(post) => (
80 <div style={{ 'margin-top': '20px' }}>
81 <b>
82 [post {postId()}] {post.title}
83 </b>
84 <p>{post.body}</p>
85 </div>
86 )}
87 </For>
88 )}
89 </QueryBoundary>
90 </div>
91 </Example>
92 )