Open History to see the last commit
1import React from "react";
2import ReactDOM from "react-dom";
3import styled from "styled-components";
4β
5import {
6 useReactQueryConfig,
7 useQuery,
8 useMutation,
9 refetchAllQueries,
10 useIsFetching,
11 _useQueries
12} from "react-query";
13β
14import "./styles.css";
15β
16const QueryStateList = styled.div`
17 display: flex;
18 padding: 0.15rem;
19 flex-wrap: wrap;
20`;
21β
22const QueryState = styled.div`
23 margin: 0.3rem;
24 color: white;
25 padding: 0.3rem;
26 font-size: 12px;
27 border-radius: 0.3rem;
28 font-weight: bold;
29 text-shadow: 0 0 10px black;
30β
31 background: ${props =>
32 props.isFetching
33 ? "orange"
34 : props.isInactive
35 ? "grey"
36 : props.isStale
37 ? "red"
38 : "green"};
39`;
40β
41const QueryKeys = styled.div`
42 font-size: 0.7rem;
43`;
44β
45const QueryKey = styled.span`
46 width: 20px;
47 height: 20px;
48 display: inline-block;
49`;
50β
51let id = 0;
52let list = [
53 "apple",
54 "banana",
55 "pineapple",
56 "grapefruit",
57 "dragonfruit",
58 "grapes"
59].map(d => ({ id: id++, name: d, notes: "These are some notes" }));
60β
61let errorRate = 0.05;
62let queryTimeMin = 1000;
63let queryTimeMax = 2000;
64β
65const fetchTodos = ({ filter } = {}) => {
66 console.log("fetchTodos", { filter });
67 return new Promise((resolve, reject) => {
68 setTimeout(() => {
69 if (Math.random() < errorRate) {
70 return reject(
71 new Error(JSON.stringify({ fetchTodos: { filter } }, null, 2))
72 );
73 }
74 resolve(list.filter(d => d.name.includes(filter)));
75 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
76 });
77};
78β
79const fetchTodoById = ({ id }) => {
80 console.log("fetchTodoById", { id });
81 return new Promise((resolve, reject) => {
82 setTimeout(() => {
83 if (Math.random() < errorRate) {
84 return reject(
85 new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2))
86 );
87 }
88 resolve(list.find(d => d.id === id));
89 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
90 });
91};
92β
93const postTodo = ({ name, notes }) => {
94 console.log("postTodo", { name, notes });
95 return new Promise((resolve, reject) => {
96 setTimeout(() => {
97 if (Math.random() < errorRate) {
98 return reject(
99 new Error(JSON.stringify({ postTodo: { name, notes } }, null, 2))
100 );
101 }
102 const todo = { name, notes, id: id++ };
103 list = [...list, todo];
104 resolve(todo);
105 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
106 });
107};
108β
109const patchTodo = todo => {
110 console.log("patchTodo", todo);
111 return new Promise((resolve, reject) => {
112 setTimeout(() => {
113 if (Math.random() < errorRate) {
114 return reject(new Error(JSON.stringify({ patchTodo: todo }, null, 2)));
115 }
116 list = list.map(d => {
117 if (d.id === todo.id) {
118 return todo;
119 }
120 return d;
121 });
122 resolve(todo);
123 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
124 });
125};
126β
127function Root() {
128 const [staleTime, setStaleTime] = React.useState(1000);
129 const [cacheTime, setCacheTime] = React.useState(3000);
130 const [localErrorRate, setErrorRate] = React.useState(errorRate);
131 const [localFetchTimeMin, setLocalFetchTimeMin] = React.useState(
132 queryTimeMin
133 );
134 const [localFetchTimeMax, setLocalFetchTimeMax] = React.useState(
135 queryTimeMax
136 );
137β
138 useReactQueryConfig({
139 staleTime,
140 cacheTime
141 // refetchAllOnWindowFocus: false
142 });
143β
144 React.useEffect(() => {
145 errorRate = localErrorRate;
146 queryTimeMin = localFetchTimeMin;
147 queryTimeMax = localFetchTimeMax;
148 }, [localErrorRate, localFetchTimeMax, localFetchTimeMin]);
149β
150 return (
151 <>
152 <p>
153 The "staleTime" and "cacheTime" durations have been altered in this
154 example to show how query stale-ness and query caching work on a
155 granular level
156 </p>
157 <div>
158 Stale Time:{" "}
159 <input
160 type="number"
161 min="0"
162 step="1000"
163 value={staleTime}
164 onChange={e => setStaleTime(parseFloat(e.target.value, 10))}
165 style={{ width: "100px" }}
166 />
167 </div>
168 <div>
169 Cache Time:{" "}
170 <input
171 type="number"
172 min="0"
173 step="1000"
174 value={cacheTime}
175 onChange={e => setCacheTime(parseFloat(e.target.value, 10))}
176 style={{ width: "100px" }}
177 />
178 </div>
179 <br />
180 <div>
181 Error Rate:{" "}
182 <input
183 type="number"
184 min="0"
185 max="1"
186 step=".05"
187 value={localErrorRate}
188 onChange={e => setErrorRate(parseFloat(e.target.value, 10))}
189 style={{ width: "100px" }}
190 />
191 </div>
192 <div>
193 Fetch Time Min:{" "}
194 <input
195 type="number"
196 min="1"
197 step="500"
198 value={localFetchTimeMin}
199 onChange={e => setLocalFetchTimeMin(parseFloat(e.target.value, 10))}
200 style={{ width: "60px" }}
201 />{" "}
202 </div>
203 <div>
204 Fetch Time Max:{" "}
205 <input
206 type="number"
207 min="1"
208 step="500"
209 value={localFetchTimeMax}
210 onChange={e => setLocalFetchTimeMax(parseFloat(e.target.value, 10))}
211 style={{ width: "60px" }}
212 />
213 </div>
214 <br />
215 <App />
216 </>
217 );
218}
219β
220function App() {
221 const [editingIndex, setEditingIndex] = React.useState(null);
222 const [views, setViews] = React.useState(["", "fruit", "grape"]);
223 // const [views, setViews] = React.useState([""]);
224β
225 const queries = _useQueries();
226β
227 return (
228 <div className="App">
229 Queries - <small>Click a query to log to console)</small>
230 <QueryStateList>
231 {queries.map(query => {
232 const {
233 queryHash,
234 state: { isFetching, isStale, isInactive }
235 } = query;
236β
237 return (
238 <QueryState
239 key={queryHash}
240 isFetching={isFetching}
241 isStale={isStale}
242 isInactive={isInactive}
243 onClick={() => {
244 console.info(query);
245 }}
246 >
247 {queryHash}
248 </QueryState>
249 );
250 })}
251 </QueryStateList>
252 <QueryKeys>
253 <span>
254 <QueryKey style={{ background: "green" }} /> Cached{" "}
255 </span>
256 <span>
257 <QueryKey style={{ background: "orange" }} /> Fetching{" "}
258 </span>
259 <span>
260 <QueryKey style={{ background: "red" }} /> Stale{" "}
261 </span>
262 <span>
263 <QueryKey style={{ background: "gray" }} /> Inactive
264 </span>
265 </QueryKeys>
266 <br />
267 <RefreshingBanner />
268 <div>
269 <button
270 onClick={async () => {
271 try {
272 refetchAllQueries({ force: true });
273 } catch {}
274 }}
275 >
276 Force Refetch All
277 </button>
278 </div>
279 <br />
280 <hr />
281 {views.map((view, index) => (
282 <div key={index}>
283 <Todos
284 initialFilter={view}
285 setEditingIndex={setEditingIndex}
286 onRemove={() => {
287 setViews(old => [...old, ""]);
288 }}
289 />
290 <br />
291 </div>
292 ))}
293 <button
294 onClick={() => {
295 setViews(old => [...old, ""]);
296 }}
297 >
298 Add Filter List
299 </button>
300 <hr />
301 {editingIndex !== null ? (
302 <>
303 <EditTodo
304 editingIndex={editingIndex}
305 setEditingIndex={setEditingIndex}
306 />
307 <hr />
308 </>
309 ) : null}
310 <AddTodo />
311 </div>
312 );
313}
314β
315function RefreshingBanner() {
316 const isFetching = useIsFetching();
317 return (
318 <div>
319 Global <code>isFetching</code>: {isFetching.toString()}
320 <br />
321 <br />
322 </div>
323 );
324}
325β
326function Todos({ initialFilter = "", setEditingIndex }) {
327 const [filter, setFilter] = React.useState(initialFilter);
328β
329 const {
330 data,
331 isLoading,
332 isFetching,
333 error,
334 failureCount,
335 refetch
336 } = useQuery(["todos", { filter }], fetchTodos);
337β
338 return (
339 <div>
340 <div>
341 <label>
342 Filter:{" "}
343 <input value={filter} onChange={e => setFilter(e.target.value)} />
344 </label>
345 </div>
346 {isLoading ? (
347 <span>Loading... (Attempt: {failureCount + 1})</span>
348 ) : error ? (
349 <span>
350 Error!{" "}
351 <button onClick={() => refetch({ disableThrow: true })}>Retry</button>
352 </span>
353 ) : (
354 <>
355 <ul>
356 {data
357 ? data.map(todo => (
358 <li key={todo.id}>
359 {todo.name}{" "}
360 <button onClick={() => setEditingIndex(todo.id)}>
361 Edit
362 </button>
363 </li>
364 ))
365 : null}
366 </ul>
367 <div>
368 {isFetching ? (
369 <span>
370 Background Refreshing... (Attempt: {failureCount + 1})
371 </span>
372 ) : (
373 <span> </span>
374 )}
375 </div>
376 </>
377 )}
378 </div>
379 );
380}
381β
382function EditTodo({ editingIndex, setEditingIndex }) {
383 // Don't attempt to query until editingIndex is truthy
384 const {
385 data,
386 isLoading,
387 isFetching,
388 error,
389 failureCount,
390 refetch
391 } = useQuery(
392 editingIndex !== null && ["todo", { id: editingIndex }],
393 fetchTodoById
394 );
395β
396 const [todo, setTodo] = React.useState(data);
397β
398 React.useEffect(() => {
399 if (editingIndex !== null && data) {
400 console.log(data);
401 setTodo(data);
402 } else {
403 setTodo();
404 }
405 }, [data, editingIndex]);
406β
407 const [mutate, mutationState] = useMutation(patchTodo, {
408 refetchQueries: ["todos"]
409 });
410β
411 const onSave = () => {
412 try {
413 mutate(todo, {
414 // Update `todos` and the individual todo queries when this mutation succeeds
415 updateQuery: ["todo", { id: editingIndex }]
416 });
417 } catch {
418 // Errors are shown in the UI
419 }
420 };
421β
422 const canEditOrSave = isLoading || mutationState.isLoading;
423β
424 return (
425 <div>
426 <div>
427 {data ? (
428 <>
429 <button onClick={() => setEditingIndex(null)}>Back</button> Editing
430 Todo "{data.name}" (#
431 {editingIndex})
432 </>
433 ) : null}
434 </div>
435 {isLoading ? (
436 <span>Loading... (Attempt: {failureCount + 1})</span>
437 ) : error ? (
438 <span>
439 Error!{" "}
440 <button onClick={() => refetch({ disableThrow: true })}>Retry</button>
441 </span>
442 ) : todo ? (
443 <>
444 <label>
445 Name:{" "}
446 <input
447 value={todo.name}
448 onChange={e =>
449 e.persist() ||
450 setTodo(old => ({ ...old, name: e.target.value }))
451 }
452 disabled={canEditOrSave}
453 />
454 </label>
455 <label>
456 Notes:{" "}
457 <input
458 value={todo.notes}
459 onChange={e =>
460 e.persist() ||
461 setTodo(old => ({ ...old, notes: e.target.value }))
462 }
463 disabled={canEditOrSave}
464 />
465 </label>
466 <div>
467 <button onClick={onSave} disabled={canEditOrSave}>
468 Save
469 </button>
470 </div>
471 <div>
472 {mutationState.isLoading
473 ? "Saving..."
474 : mutationState.error
475 ? String(mutationState.error)
476 : mutationState.data
477 ? "Saved!"
478 : null}
479 </div>
480 <div>
481 {isFetching ? (
482 <span>
483 Background Refreshing... (Attempt: {failureCount + 1})
484 </span>
485 ) : (
486 <span> </span>
487 )}
488 </div>
489 </>
490 ) : null}
491 </div>
492 );
493}
494β
495function AddTodo() {
496 const [name, setName] = React.useState("");
497β
498 const [mutate, { isLoading, error, data }] = useMutation(postTodo, {
499 refetchQueries: ["todos"]
500 });
501β
502 return (
503 <div>
504 <input
505 value={name}
506 onChange={e => setName(e.target.value)}
507 disabled={isLoading}
508 />
509 <button onClick={() => mutate({ name })} disabled={isLoading || !name}>
510 Add Todo
511 </button>
512 <div>
513 {isLoading
514 ? "Saving..."
515 : error
516 ? String(error)
517 : data
518 ? "Saved!"
519 : null}
520 </div>
521 </div>
522 );
523}
524β
525const rootElement = document.getElementById("root");
526ReactDOM.render(<Root />, rootElement);