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

index.tsx

375 lines9.5 KB

1import { render } from 'preact'
2import { useEffect, useState } from 'preact/hooks'
3import {
4 QueryClient,
5 QueryClientProvider,
6 useMutation,
7 useQuery,
8 useQueryClient,
9} from '@tanstack/preact-query'
10import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
11import { serverConfig } from './services/todos/api'
12import { todosMutations, todosQueries } from './services/todos/queries'
13import type { Todo } from './services/todos/types'
14import type { TargetedEvent } from 'preact'
15import './styles.css'
16​
17const initialStaleTime = 1000
18const initialGcTime = 3000
19​
20const queryClient = new QueryClient({
21 defaultOptions: {
22 queries: {
23 staleTime: initialStaleTime,
24 gcTime: initialGcTime,
25 },
26 },
27})
28​
29function onNumberChange(setValue: (value: number) => void) {
30 return (event: TargetedEvent<HTMLInputElement>) => {
31 const value = event.currentTarget.valueAsNumber
32 if (!Number.isNaN(value)) {
33 setValue(value)
34 }
35 }
37​
38function Root() {
39 const [staleTime, setStaleTime] = useState(initialStaleTime)
40 const [gcTime, setGcTime] = useState(initialGcTime)
41 const [localErrorRate, setLocalErrorRate] = useState(serverConfig.errorRate)
42 const [localFetchTimeMin, setLocalFetchTimeMin] = useState(
43 serverConfig.queryTimeMin,
44 )
45 const [localFetchTimeMax, setLocalFetchTimeMax] = useState(
46 serverConfig.queryTimeMax,
47 )
48​
49 useEffect(() => {
50 serverConfig.errorRate = localErrorRate
51 serverConfig.queryTimeMin = localFetchTimeMin
52 serverConfig.queryTimeMax = localFetchTimeMax
53 }, [localErrorRate, localFetchTimeMax, localFetchTimeMin])
54​
55 useEffect(() => {
56 queryClient.setDefaultOptions({
57 queries: {
58 staleTime,
59 gcTime,
60 },
61 })
62 }, [gcTime, staleTime])
63​
64 return (
65 <QueryClientProvider client={queryClient}>
66 <p>
67 The "staleTime" and "gcTime" durations have been altered in this example
68 to show how query stale-ness and query caching work on a granular level
69 </p>
70 <div>
71 Stale Time:{' '}
72 <input
73 type="number"
74 min="0"
75 step="1000"
76 defaultValue={staleTime}
77 onInput={onNumberChange(setStaleTime)}
78 style={{ width: '100px' }}
79 />
80 </div>
81 <div>
82 Garbage collection Time:{' '}
83 <input
84 type="number"
85 min="0"
86 step="1000"
87 defaultValue={gcTime}
88 onInput={onNumberChange(setGcTime)}
89 style={{ width: '100px' }}
90 />
91 </div>
92 <br />
93 <div>
94 Error Rate:{' '}
95 <input
96 type="number"
97 min="0"
98 max="1"
99 step=".05"
100 defaultValue={localErrorRate}
101 onInput={onNumberChange(setLocalErrorRate)}
102 style={{ width: '100px' }}
103 />
104 </div>
105 <div>
106 Fetch Time Min:{' '}
107 <input
108 type="number"
109 min="1"
110 step="500"
111 defaultValue={localFetchTimeMin}
112 onInput={onNumberChange(setLocalFetchTimeMin)}
113 style={{ width: '60px' }}
114 />{' '}
115 </div>
116 <div>
117 Fetch Time Max:{' '}
118 <input
119 type="number"
120 min="1"
121 step="500"
122 defaultValue={localFetchTimeMax}
123 onInput={onNumberChange(setLocalFetchTimeMax)}
124 style={{ width: '60px' }}
125 />
126 </div>
127 <br />
128 <App />
129 <br />
130 <PreactQueryDevtools initialIsOpen />
131 </QueryClientProvider>
132 )
134​
135function App() {
136 const queryClient = useQueryClient()
137 const [editingIndex, setEditingIndex] = useState<number | null>(null)
138 const [views, setViews] = useState(['', 'fruit', 'grape'])
139​
140 return (
141 <div className="App">
142 <div>
143 <button onClick={() => queryClient.invalidateQueries()}>
144 Force Refetch All
145 </button>
146 </div>
147 <br />
148 <hr />
149 {views.map((view, index) => (
150 <div key={index}>
151 <Todos initialFilter={view} setEditingIndex={setEditingIndex} />
152 <br />
153 </div>
154 ))}
155 <button
156 onClick={() => {
157 setViews((old) => [...old, ''])
158 }}
159 >
160 Add Filter List
161 </button>
162 <hr />
163 {editingIndex !== null ? (
164 <>
165 <EditTodo
166 key={editingIndex}
167 editingIndex={editingIndex}
168 setEditingIndex={setEditingIndex}
169 />
170 <hr />
171 </>
172 ) : null}
173 <AddTodo />
174 </div>
175 )
177​
178function Todos({
179 initialFilter = '',
180 setEditingIndex,
181}: {
182 initialFilter: string
183 setEditingIndex: (editingIndex: number | null) => void
184}) {
185 const [filter, setFilter] = useState(initialFilter)
186​
187 const { status, data, isFetching, error, failureCount, refetch } = useQuery(
188 todosQueries.list(filter),
189 )
190​
191 return (
192 <div>
193 <div>
194 <label>
195 Filter:{' '}
196 <input
197 value={filter}
198 onInput={(e) => setFilter(e.currentTarget.value)}
199 />
200 </label>
201 </div>
202 {status === 'pending' ? (
203 <span>Loading... (Attempt: {failureCount + 1})</span>
204 ) : status === 'error' ? (
205 <span>
206 Error: {error.message}
207 <br />
208 <button onClick={() => refetch()}>Retry</button>
209 </span>
210 ) : (
211 <>
212 <ul>
213 {data.map((todo) => (
214 <li key={todo.id}>
215 {todo.name}{' '}
216 <button onClick={() => setEditingIndex(todo.id)}>Edit</button>
217 </li>
218 ))}
219 </ul>
220 <div>
221 {isFetching ? (
222 <span>
223 Background Refreshing... (Attempt: {failureCount + 1})
224 </span>
225 ) : (
226 <span>&nbsp;</span>
227 )}
228 </div>
229 </>
230 )}
231 </div>
232 )
234​
235function EditTodo({
236 editingIndex,
237 setEditingIndex,
238}: {
239 editingIndex: number
240 setEditingIndex: (editingIndex: number | null) => void
241}) {
242 const queryClient = useQueryClient()
243​
244 const { status, data, isFetching, failureCount, refetch } = useQuery(
245 todosQueries.detail(editingIndex),
246 )
247​
248 const [draft, setDraft] = useState<Partial<Omit<Todo, 'id'>>>({})
249​
250 const saveMutation = useMutation({
251 ...todosMutations.update(),
252 onSuccess: (todo) => {
253 // Update `todos` and the individual todo queries when this mutation succeeds
254 queryClient.invalidateQueries({ queryKey: todosQueries.lists() })
255 queryClient.setQueryData(todosQueries.detail(editingIndex).queryKey, todo)
256 setDraft({})
257 },
258 })
259​
260 const disableEditSave =
261 status === 'pending' || saveMutation.status === 'pending'
262​
263 return (
264 <div>
265 <div>
266 {data ? (
267 <>
268 <button onClick={() => setEditingIndex(null)}>Back</button> Editing
269 Todo "{data.name}" (#
270 {editingIndex})
271 </>
272 ) : null}
273 </div>
274 {status === 'pending' ? (
275 <span>Loading... (Attempt: {failureCount + 1})</span>
276 ) : status === 'error' ? (
277 <span>
278 Error! <button onClick={() => refetch()}>Retry</button>
279 </span>
280 ) : (
281 <>
282 <label>
283 Name:{' '}
284 <input
285 value={draft.name ?? data.name}
286 onInput={(e) =>
287 setDraft((old) => ({ ...old, name: e.currentTarget.value }))
288 }
289 disabled={disableEditSave}
290 />
291 </label>
292 <label>
293 Notes:{' '}
294 <input
295 value={draft.notes ?? data.notes}
296 onInput={(e) =>
297 setDraft((old) => ({ ...old, notes: e.currentTarget.value }))
298 }
299 disabled={disableEditSave}
300 />
301 </label>
302 <div>
303 <button
304 onClick={() => saveMutation.mutate({ ...data, ...draft })}
305 disabled={disableEditSave}
306 >
307 Save
308 </button>
309 </div>
310 <div>
311 {saveMutation.status === 'pending'
312 ? 'Saving...'
313 : saveMutation.status === 'error'
314 ? saveMutation.error.message
315 : saveMutation.status === 'success'
316 ? 'Saved!'
317 : null}
318 </div>
319 <div>
320 {isFetching ? (
321 <span>
322 Background Refreshing... (Attempt: {failureCount + 1})
323 </span>
324 ) : (
325 <span>&nbsp;</span>
326 )}
327 </div>
328 </>
329 )}
330 </div>
331 )
333​
334function AddTodo() {
335 const queryClient = useQueryClient()
336 const [name, setName] = useState('')
337​
338 const addMutation = useMutation({
339 ...todosMutations.create(),
340 onSuccess: () => {
341 queryClient.invalidateQueries({ queryKey: todosQueries.lists() })
342 },
343 })
344​
345 return (
346 <div>
347 <input
348 value={name}
349 onInput={(e) => setName(e.currentTarget.value)}
350 disabled={addMutation.status === 'pending'}
351 />
352 <button
353 onClick={() => {
354 addMutation.mutate({ name, notes: 'These are some notes' })
355 }}
356 disabled={addMutation.status === 'pending' || !name}
357 >
358 Add Todo
359 </button>
360 <div>
361 {addMutation.status === 'pending'
362 ? 'Saving...'
363 : addMutation.status === 'error'
364 ? addMutation.error.message
365 : addMutation.status === 'success'
366 ? 'Saved!'
367 : null}
368 </div>
369 </div>
370 )
372​
373const rootElement = document.getElementById('root')
374if (!rootElement) throw new Error('Missing #root element')
375render(<Root />, rootElement)