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

index.tsx

373 lines9.5 KB

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