Open History to see the last commit
1import React from 'react'
2import ReactDOM from 'react-dom/client'
3β
4import {
5 QueryClient,
6 QueryClientProvider,
7 useQuery,
8 useQueryClient,
9 useMutation,
10} from '@tanstack/react-query'
11β
12import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
13β
14import './styles.css'
15β
16let id = 0
17let list = [
18 'apple',
19 'banana',
20 'pineapple',
21 'grapefruit',
22 'dragonfruit',
23 'grapes',
24].map((d) => ({ id: id++, name: d, notes: 'These are some notes' }))
25β
26let errorRate = 0.05
27let queryTimeMin = 1000
28let queryTimeMax = 2000
29β
30const queryClient = new QueryClient()
31β
32function Root() {
33 const [staleTime, setStaleTime] = React.useState(1000)
34 const [cacheTime, setCacheTime] = React.useState(3000)
35 const [localErrorRate, setErrorRate] = React.useState(errorRate)
36 const [localFetchTimeMin, setLocalFetchTimeMin] = React.useState(queryTimeMin)
37 const [localFetchTimeMax, setLocalFetchTimeMax] = React.useState(queryTimeMax)
38β
39 React.useEffect(() => {
40 errorRate = localErrorRate
41 queryTimeMin = localFetchTimeMin
42 queryTimeMax = localFetchTimeMax
43 }, [localErrorRate, localFetchTimeMax, localFetchTimeMin])
44β
45 React.useEffect(() => {
46 queryClient.setDefaultOptions({
47 queries: {
48 staleTime,
49 cacheTime,
50 },
51 })
52 }, [cacheTime, staleTime])
53β
54 return (
55 <QueryClientProvider client={queryClient}>
56 <p>
57 The "staleTime" and "cacheTime" durations have been altered in this
58 example to show how query stale-ness and query caching work on a
59 granular level
60 </p>
61 <div>
62 Stale Time:{' '}
63 <input
64 type="number"
65 min="0"
66 step="1000"
67 value={staleTime}
68 onChange={(e) => setStaleTime(parseFloat(e.target.value, 10))}
69 style={{ width: '100px' }}
70 />
71 </div>
72 <div>
73 Cache Time:{' '}
74 <input
75 type="number"
76 min="0"
77 step="1000"
78 value={cacheTime}
79 onChange={(e) => setCacheTime(parseFloat(e.target.value, 10))}
80 style={{ width: '100px' }}
81 />
82 </div>
83 <br />
84 <div>
85 Error Rate:{' '}
86 <input
87 type="number"
88 min="0"
89 max="1"
90 step=".05"
91 value={localErrorRate}
92 onChange={(e) => setErrorRate(parseFloat(e.target.value, 10))}
93 style={{ width: '100px' }}
94 />
95 </div>
96 <div>
97 Fetch Time Min:{' '}
98 <input
99 type="number"
100 min="1"
101 step="500"
102 value={localFetchTimeMin}
103 onChange={(e) => setLocalFetchTimeMin(parseFloat(e.target.value, 10))}
104 style={{ width: '60px' }}
105 />{' '}
106 </div>
107 <div>
108 Fetch Time Max:{' '}
109 <input
110 type="number"
111 min="1"
112 step="500"
113 value={localFetchTimeMax}
114 onChange={(e) => setLocalFetchTimeMax(parseFloat(e.target.value, 10))}
115 style={{ width: '60px' }}
116 />
117 </div>
118 <br />
119 <App />
120 <br />
121 <ReactQueryDevtools initialIsOpen />
122 </QueryClientProvider>
123 )
124}
125β
126function App() {
127 const queryClient = useQueryClient()
128 const [editingIndex, setEditingIndex] = React.useState(null)
129 const [views, setViews] = React.useState(['', 'fruit', 'grape'])
130 // const [views, setViews] = React.useState([""]);
131β
132 return (
133 <div className="App">
134 <div>
135 <button onClick={() => queryClient.invalidateQueries()}>
136 Force Refetch All
137 </button>
138 </div>
139 <br />
140 <hr />
141 {views.map((view, index) => (
142 <div key={index}>
143 <Todos
144 initialFilter={view}
145 setEditingIndex={setEditingIndex}
146 onRemove={() => {
147 setViews((old) => [...old, ''])
148 }}
149 />
150 <br />
151 </div>
152 ))}
153 <button
154 onClick={() => {
155 setViews((old) => [...old, ''])
156 }}
157 >
158 Add Filter List
159 </button>
160 <hr />
161 {editingIndex !== null ? (
162 <>
163 <EditTodo
164 editingIndex={editingIndex}
165 setEditingIndex={setEditingIndex}
166 />
167 <hr />
168 </>
169 ) : null}
170 <AddTodo />
171 </div>
172 )
173}
174β
175function Todos({ initialFilter = '', setEditingIndex }) {
176 const [filter, setFilter] = React.useState(initialFilter)
177β
178 const { status, data, isFetching, error, failureCount, refetch } = useQuery({
179 queryKey: ['todos', { filter }],
180 queryFn: fetchTodos,
181 })
182β
183 return (
184 <div>
185 <div>
186 <label>
187 Filter:{' '}
188 <input value={filter} onChange={(e) => setFilter(e.target.value)} />
189 </label>
190 </div>
191 {status === 'loading' ? (
192 <span>Loading... (Attempt: {failureCount + 1})</span>
193 ) : status === 'error' ? (
194 <span>
195 Error: {error.message}
196 <br />
197 <button onClick={() => refetch()}>Retry</button>
198 </span>
199 ) : (
200 <>
201 <ul>
202 {data
203 ? data.map((todo) => (
204 <li key={todo.id}>
205 {todo.name}{' '}
206 <button onClick={() => setEditingIndex(todo.id)}>
207 Edit
208 </button>
209 </li>
210 ))
211 : null}
212 </ul>
213 <div>
214 {isFetching ? (
215 <span>
216 Background Refreshing... (Attempt: {failureCount + 1})
217 </span>
218 ) : (
219 <span> </span>
220 )}
221 </div>
222 </>
223 )}
224 </div>
225 )
226}
227β
228function EditTodo({ editingIndex, setEditingIndex }) {
229 const queryClient = useQueryClient()
230β
231 // Don't attempt to query until editingIndex is truthy
232 const { status, data, isFetching, error, failureCount, refetch } = useQuery({
233 queryKey: ['todo', { id: editingIndex }],
234 queryFn: () => fetchTodoById({ id: editingIndex }),
235 enabled: editingIndex !== null,
236 })
237β
238 const [todo, setTodo] = React.useState(data || {})
239β
240 React.useEffect(() => {
241 if (editingIndex !== null && data) {
242 setTodo(data)
243 } else {
244 setTodo({})
245 }
246 }, [data, editingIndex])
247β
248 const saveMutation = useMutation({
249 mutationFn: patchTodo,
250 onSuccess: (data) => {
251 // Update `todos` and the individual todo queries when this mutation succeeds
252 queryClient.invalidateQueries({ queryKey: ['todos'] })
253 queryClient.setQueryData(['todo', { id: editingIndex }], data)
254 },
255 })
256β
257 const onSave = () => {
258 saveMutation.mutate(todo)
259 }
260β
261 const disableEditSave =
262 status === 'loading' || saveMutation.status === 'loading'
263β
264 return (
265 <div>
266 <div>
267 {data ? (
268 <>
269 <button onClick={() => setEditingIndex(null)}>Back</button> Editing
270 Todo "{data.name}" (#
271 {editingIndex})
272 </>
273 ) : null}
274 </div>
275 {status === 'loading' ? (
276 <span>Loading... (Attempt: {failureCount + 1})</span>
277 ) : error ? (
278 <span>
279 Error! <button onClick={() => refetch()}>Retry</button>
280 </span>
281 ) : (
282 <>
283 <label>
284 Name:{' '}
285 <input
286 value={todo.name}
287 onChange={(e) =>
288 e.persist() ||
289 setTodo((old) => ({ ...old, name: e.target.value }))
290 }
291 disabled={disableEditSave}
292 />
293 </label>
294 <label>
295 Notes:{' '}
296 <input
297 value={todo.notes}
298 onChange={(e) =>
299 e.persist() ||
300 setTodo((old) => ({ ...old, notes: e.target.value }))
301 }
302 disabled={disableEditSave}
303 />
304 </label>
305 <div>
306 <button onClick={onSave} disabled={disableEditSave}>
307 Save
308 </button>
309 </div>
310 <div>
311 {saveMutation.status === 'loading'
312 ? 'Saving...'
313 : saveMutation.status === 'error'
314 ? saveMutation.error.message
315 : 'Saved!'}
316 </div>
317 <div>
318 {isFetching ? (
319 <span>
320 Background Refreshing... (Attempt: {failureCount + 1})
321 </span>
322 ) : (
323 <span> </span>
324 )}
325 </div>
326 </>
327 )}
328 </div>
329 )
330}
331β
332function AddTodo() {
333 const queryClient = useQueryClient()
334 const [name, setName] = React.useState('')
335β
336 const addMutation = useMutation({
337 mutationFn: postTodo,
338 onSuccess: () => {
339 queryClient.invalidateQueries({ queryKey: ['todos'] })
340 },
341 })
342β
343 return (
344 <div>
345 <input
346 value={name}
347 onChange={(e) => setName(e.target.value)}
348 disabled={addMutation.status === 'loading'}
349 />
350 <button
351 onClick={() => {
352 addMutation.mutate({ name })
353 }}
354 disabled={addMutation.status === 'loading' || !name}
355 >
356 Add Todo
357 </button>
358 <div>
359 {addMutation.status === 'loading'
360 ? 'Saving...'
361 : addMutation.status === 'error'
362 ? addMutation.error.message
363 : 'Saved!'}
364 </div>
365 </div>
366 )
367}
368β
369function fetchTodos({ signal, queryKey: [, { filter }] }) {
370 console.info('fetchTodos', { filter })
371β
372 if (signal) {
373 signal.addEventListener('abort', () => {
374 console.info('cancelled', filter)
375 })
376 }
377β
378 return new Promise((resolve, reject) => {
379 setTimeout(() => {
380 if (Math.random() < errorRate) {
381 return reject(
382 new Error(JSON.stringify({ fetchTodos: { filter } }, null, 2)),
383 )
384 }
385 resolve(list.filter((d) => d.name.includes(filter)))
386 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin))
387 })
388}
389β
390function fetchTodoById({ id }) {
391 console.info('fetchTodoById', { id })
392 return new Promise((resolve, reject) => {
393 setTimeout(() => {
394 if (Math.random() < errorRate) {
395 return reject(
396 new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2)),
397 )
398 }
399 resolve(list.find((d) => d.id === id))
400 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin))
401 })
402}
403β
404function postTodo({ name, notes }) {
405 console.info('postTodo', { name, notes })
406 return new Promise((resolve, reject) => {
407 setTimeout(() => {
408 if (Math.random() < errorRate) {
409 return reject(
410 new Error(JSON.stringify({ postTodo: { name, notes } }, null, 2)),
411 )
412 }
413 const todo = { name, notes, id: id++ }
414 list = [...list, todo]
415 resolve(todo)
416 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin))
417 })
418}
419β
420function patchTodo(todo) {
421 console.info('patchTodo', todo)
422 return new Promise((resolve, reject) => {
423 setTimeout(() => {
424 if (Math.random() < errorRate) {
425 return reject(new Error(JSON.stringify({ patchTodo: todo }, null, 2)))
426 }
427 list = list.map((d) => {
428 if (d.id === todo.id) {
429 return todo
430 }
431 return d
432 })
433 resolve(todo)
434 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin))
435 })
436}
437β
438const rootElement = document.getElementById('root')
439ReactDOM.createRoot(rootElement).render(<Root />)