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