Open History to see the last commit
1import { render } from 'preact'
2import { useState } from 'preact/hooks'
3import {
4 QueryClient,
5 QueryClientProvider,
6 useQuery,
7 useQueryClient,
8} from '@tanstack/preact-query'
9import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
10import type { QueryKey } from '@tanstack/preact-query'
11β
12type Post = {
13 id: number
14 title: string
15 body: string
16}
17β
18// Define a default query function that will receive the query key
19const defaultQueryFn = async ({ queryKey }: { queryKey: QueryKey }) => {
20 const response = await fetch(
21 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
22 )
23 if (!response.ok) throw new Error('Failed to fetch data')
24 return await response.json()
25}
26β
27// provide the default query function to your app via the query client
28const queryClient = new QueryClient({
29 defaultOptions: {
30 queries: {
31 queryFn: defaultQueryFn,
32 },
33 },
34})
35β
36function App() {
37 const [postId, setPostId] = useState(-1)
38β
39 return (
40 <QueryClientProvider client={queryClient}>
41 <p>
42 As you visit the posts below, you will notice them in a loading state
43 the first time you load them. However, after you return to this list and
44 click on any posts you have already visited again, you will see them
45 load instantly and background refresh right before your eyes!{' '}
46 <strong>
47 (You may need to throttle your network speed to simulate longer
48 loading sequences)
49 </strong>
50 </p>
51 {postId > -1 ? (
52 <Post postId={postId} setPostId={setPostId} />
53 ) : (
54 <Posts setPostId={setPostId} />
55 )}
56 <PreactQueryDevtools initialIsOpen />
57 </QueryClientProvider>
58 )
59}
60β
61function Posts({ setPostId }: { setPostId: (postId: number) => void }) {
62 const queryClient = useQueryClient()
63β
64 // All you have to do now is pass a key!
65 const { status, data, error, isFetching } = useQuery<Array<Post>>({
66 queryKey: ['/posts'],
67 })
68β
69 return (
70 <div>
71 <h1>Posts</h1>
72 <div>
73 {status === 'pending' ? (
74 'Loading...'
75 ) : status === 'error' ? (
76 <span>Error: {error.message}</span>
77 ) : (
78 <>
79 <div>
80 {data.map((post) => (
81 <p key={post.id}>
82 <a
83 onClick={() => setPostId(post.id)}
84 href="#"
85 style={
86 // We can use the queryCache here to show bold links for
87 // ones that are cached
88 queryClient.getQueryData([`/posts/${post.id}`])
89 ? {
90 fontWeight: 'bold',
91 color: 'green',
92 }
93 : {}
94 }
95 >
96 {post.title}
97 </a>
98 </p>
99 ))}
100 </div>
101 <div>{isFetching ? 'Background Updating...' : ' '}</div>
102 </>
103 )}
104 </div>
105 </div>
106 )
107}
108β
109function Post({
110 postId,
111 setPostId,
112}: {
113 postId: number
114 setPostId: (postId: number) => void
115}) {
116 // You can even leave out the queryFn and just go straight into options
117 const { status, data, error, isFetching } = useQuery<Post>({
118 queryKey: [`/posts/${postId}`],
119 enabled: !!postId,
120 })
121β
122 return (
123 <div>
124 <div>
125 <a onClick={() => setPostId(-1)} href="#">
126 Back
127 </a>
128 </div>
129 {!postId || status === 'pending' ? (
130 'Loading...'
131 ) : status === 'error' ? (
132 <span>Error: {error.message}</span>
133 ) : (
134 <>
135 <h1>{data.title}</h1>
136 <div>
137 <p>{data.body}</p>
138 </div>
139 <div>{isFetching ? 'Background Updating...' : ' '}</div>
140 </>
141 )}
142 </div>
143 )
144}
145β
146const rootElement = document.getElementById('root')
147if (!rootElement) throw new Error('Missing #root element')
148render(<App />, rootElement)