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

index.tsx

409 lines10.7 KB

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