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

index.tsx

122 lines3.3 KB

1import {
2 QueryClient,
3 QueryClientProvider,
4 useQuery,
5 useQueryClient,
6} from '@tanstack/preact-query'
7import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
8import { render } from 'preact'
9import { useState } from 'preact/hooks'
10import { postsQueries } from './services/posts/queries'
11​
12const queryClient = new QueryClient()
13​
14function App() {
15 const [postId, setPostId] = useState<string | null>(null)
16​
17 return (
18 <QueryClientProvider client={queryClient}>
19 <p>
20 As you visit the posts below, you will notice them in a loading state
21 the first time you load them. However, after you return to this list and
22 click on any posts you have already visited again, you will see them
23 load instantly and background refresh right before your eyes!{' '}
24 <strong>
25 (You may need to throttle your network speed to simulate longer
26 loading sequences)
27 </strong>
28 </p>
29 {postId !== null ? (
30 <Post postId={postId} setPostId={setPostId} />
31 ) : (
32 <Posts setPostId={setPostId} />
33 )}
34 <PreactQueryDevtools initialIsOpen />
35 </QueryClientProvider>
36 )
38​
39function Posts({ setPostId }: { setPostId: (postId: string | null) => void }) {
40 const queryClient = useQueryClient()
41 const { status, data, error, isFetching } = useQuery(postsQueries.list())
42​
43 return (
44 <div>
45 <h1>Posts</h1>
46 <div>
47 {status === 'pending' ? (
48 'Loading...'
49 ) : status === 'error' ? (
50 <span>Error: {error.message}</span>
51 ) : (
52 <>
53 <div>
54 {data.map((post) => (
55 <p key={post.id}>
56 <a
57 onClick={() => setPostId(post.id)}
58 href="#"
59 style={
60 // We can find the existing query data here to show bold links for
61 // ones that are cached
62 queryClient.getQueryData(
63 postsQueries.detail(post.id).queryKey,
64 )
65 ? {
66 fontWeight: 'bold',
67 color: 'green',
68 }
69 : {}
70 }
71 >
72 {post.title}
73 </a>
74 </p>
75 ))}
76 </div>
77 <div>{isFetching ? 'Background Updating...' : ' '}</div>
78 </>
79 )}
80 </div>
81 </div>
82 )
84​
85function Post({
86 postId,
87 setPostId,
88}: {
89 postId: string
90 setPostId: (postId: string | null) => void
91}) {
92 const { status, data, error, isFetching } = useQuery(
93 postsQueries.detail(postId),
94 )
95​
96 return (
97 <div>
98 <div>
99 <a onClick={() => setPostId(null)} href="#">
100 Back
101 </a>
102 </div>
103 {status === 'pending' ? (
104 'Loading...'
105 ) : status === 'error' ? (
106 <span>Error: {error.message}</span>
107 ) : (
108 <>
109 <h1>{data.title}</h1>
110 <div>
111 <p>{data.body}</p>
112 </div>
113 <div>{isFetching ? 'Background Updating...' : ' '}</div>
114 </>
115 )}
116 </div>
117 )
119​
120const rootElement = document.getElementById('root')
121if (!rootElement) throw new Error('Missing #root element')
122render(<App />, rootElement)