Open History to see the last commit
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 { fetchPost } from '~/utils/api'
7β
8export interface PostViewerProps {
9 deferStream?: boolean
10 sleep?: number
11 simulateError?: boolean
12}
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 queryKey: ['posts', postId(), props.sleep, shouldSimulateError()],
25 queryFn: () =>
26 fetchPost({
27 postId: postId(),
28 sleep: props.sleep,
29 simulateError: shouldSimulateError(),
30 }),
31 deferStream: props.deferStream,
32 throwOnError: true,
33 }))
34β
35 return (
36 <Example
37 title="Post Query"
38 deferStream={props.deferStream}
39 sleep={props.sleep}
40 >
41 <div style={{ 'margin-top': '20px' }}>
42 <button
43 onClick={() => {
44 setPostId(Math.max(postId() - 1, 1))
45 resetErrorBoundaries()
46 }}
47 >
48 Previous Post
49 </button>
50 <button
51 onClick={() => {
52 setPostId(Math.min(postId() + 1, 100))
53 resetErrorBoundaries()
54 }}
55 >
56 Next Post
57 </button>
58 </div>
59β
60 {/* NOTE: without this extra wrapping div, for some reason solid ends up printing two errors... feels like a bug in solid. */}
61 <div>
62 <QueryBoundary
63 query={query}
64 loadingFallback={<div class="loader">loading post...</div>}
65 errorFallback={(err, retry) => (
66 <div>
67 <div class="error">{err.message}</div>
68 <button
69 onClick={() => {
70 setSimulateError(false)
71 retry()
72 }}
73 >
74 retry
75 </button>
76 </div>
77 )}
78 >
79 {(posts) => (
80 <For each={posts}>
81 {(post) => (
82 <div style={{ 'margin-top': '20px' }}>
83 <b>
84 [post {postId()}] {post.title}
85 </b>
86 <p>{post.body}</p>
87 </div>
88 )}
89 </For>
90 )}
91 </QueryBoundary>
92 </div>
93 </Example>
94 )
95}