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