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