Open History to see the last commit
1import React from "react";
2import ReactDOM from "react-dom";
3β
4import {
5 ReactQueryConfigProvider,
6 useQuery,
7 useMutation,
8 queryCache
9} from "react-query";
10β
11import { ReactQueryDevtools } from "react-query-devtools";
12β
13import "./styles.css";
14β
15let id = 0;
16let list = [
17 "apple",
18 "banana",
19 "pineapple",
20 "grapefruit",
21 "dragonfruit",
22 "grapes"
23].map(d => ({ id: id++, name: d, notes: "These are some notes" }));
24β
25let errorRate = 0.05;
26let queryTimeMin = 1000;
27let queryTimeMax = 2000;
28β
29function Root() {
30 const [staleTime, setStaleTime] = React.useState(1000);
31 const [cacheTime, setCacheTime] = React.useState(3000);
32 const [localErrorRate, setErrorRate] = React.useState(errorRate);
33 const [localFetchTimeMin, setLocalFetchTimeMin] = React.useState(
34 queryTimeMin
35 );
36 const [localFetchTimeMax, setLocalFetchTimeMax] = React.useState(
37 queryTimeMax
38 );
39β
40 React.useEffect(() => {
41 errorRate = localErrorRate;
42 queryTimeMin = localFetchTimeMin;
43 queryTimeMax = localFetchTimeMax;
44 }, [localErrorRate, localFetchTimeMax, localFetchTimeMin]);
45β
46 const queryConfig = React.useMemo(
47 () => ({
48 staleTime,
49 cacheTime
50 }),
51 [cacheTime, staleTime]
52 );
53β
54 return (
55 <ReactQueryConfigProvider config={queryConfig}>
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 />
122 </ReactQueryConfigProvider>
123 );
124}
125β
126function App() {
127 const [editingIndex, setEditingIndex] = React.useState(null);
128 const [views, setViews] = React.useState(["", "fruit", "grape"]);
129 // const [views, setViews] = React.useState([""]);
130β
131 return (
132 <div className="App">
133 <div>
134 <button onClick={() => queryCache.refetchQueries(true)}>
135 Force Refetch All
136 </button>
137 </div>
138 <br />
139 <hr />
140 {views.map((view, index) => (
141 <div key={index}>
142 <Todos
143 initialFilter={view}
144 setEditingIndex={setEditingIndex}
145 onRemove={() => {
146 setViews(old => [...old, ""]);
147 }}
148 />
149 <br />
150 </div>
151 ))}
152 <button
153 onClick={() => {
154 setViews(old => [...old, ""]);
155 }}
156 >
157 Add Filter List
158 </button>
159 <hr />
160 {editingIndex !== null ? (
161 <>
162 <EditTodo
163 editingIndex={editingIndex}
164 setEditingIndex={setEditingIndex}
165 />
166 <hr />
167 </>
168 ) : null}
169 <AddTodo />
170 </div>
171 );
172}
173β
174function Todos({ initialFilter = "", setEditingIndex }) {
175 const [filter, setFilter] = React.useState(initialFilter);
176β
177 const { status, data, isFetching, error, failureCount, refetch } = useQuery(
178 ["todos", { filter }],
179 fetchTodos
180 );
181β
182 return (
183 <div>
184 <div>
185 <label>
186 Filter:{" "}
187 <input value={filter} onChange={e => setFilter(e.target.value)} />
188 </label>
189 </div>
190 {status === "loading" ? (
191 <span>Loading... (Attempt: {failureCount + 1})</span>
192 ) : status === "error" ? (
193 <span>
194 Error: {error.message}
195 <br />
196 <button onClick={() => refetch({ disableThrow: true })}>Retry</button>
197 </span>
198 ) : (
199 <>
200 <ul>
201 {data
202 ? data.map(todo => (
203 <li key={todo.id}>
204 {todo.name}{" "}
205 <button onClick={() => setEditingIndex(todo.id)}>
206 Edit
207 </button>
208 </li>
209 ))
210 : null}
211 </ul>
212 <div>
213 {isFetching ? (
214 <span>
215 Background Refreshing... (Attempt: {failureCount + 1})
216 </span>
217 ) : (
218 <span> </span>
219 )}
220 </div>
221 </>
222 )}
223 </div>
224 );
225}
226β
227function EditTodo({ editingIndex, setEditingIndex }) {
228 // Don't attempt to query until editingIndex is truthy
229 const { status, data, isFetching, error, failureCount, refetch } = useQuery(
230 editingIndex !== null && ["todo", { id: editingIndex }],
231 fetchTodoById
232 );
233β
234 const [todo, setTodo] = React.useState(data || {});
235β
236 React.useEffect(() => {
237 if (editingIndex !== null && data) {
238 setTodo(data);
239 } else {
240 setTodo({});
241 }
242 }, [data, editingIndex]);
243β
244 const [mutate, mutationState] = useMutation(patchTodo, {
245 onSuccess: data => {
246 // Update `todos` and the individual todo queries when this mutation succeeds
247 queryCache.refetchQueries("todos");
248 queryCache.setQueryData(["todo", { id: editingIndex }], data);
249 }
250 });
251β
252 const onSave = () => mutate(todo);
253β
254 const disableEditSave =
255 status === "loading" || mutationState.status === "loading";
256β
257 return (
258 <div>
259 <div>
260 {data ? (
261 <>
262 <button onClick={() => setEditingIndex(null)}>Back</button> Editing
263 Todo "{data.name}" (#
264 {editingIndex})
265 </>
266 ) : null}
267 </div>
268 {status === "loading" ? (
269 <span>Loading... (Attempt: {failureCount + 1})</span>
270 ) : error ? (
271 <span>
272 Error!{" "}
273 <button onClick={() => refetch({ disableThrow: true })}>Retry</button>
274 </span>
275 ) : (
276 <>
277 <label>
278 Name:{" "}
279 <input
280 value={todo.name}
281 onChange={e =>
282 e.persist() ||
283 setTodo(old => ({ ...old, name: e.target.value }))
284 }
285 disabled={disableEditSave}
286 />
287 </label>
288 <label>
289 Notes:{" "}
290 <input
291 value={todo.notes}
292 onChange={e =>
293 e.persist() ||
294 setTodo(old => ({ ...old, notes: e.target.value }))
295 }
296 disabled={disableEditSave}
297 />
298 </label>
299 <div>
300 <button onClick={onSave} disabled={disableEditSave}>
301 Save
302 </button>
303 </div>
304 <div>
305 {mutationState.status === "loading"
306 ? "Saving..."
307 : mutationState.status === "error"
308 ? mutationState.error.message
309 : "Saved!"}
310 </div>
311 <div>
312 {isFetching ? (
313 <span>
314 Background Refreshing... (Attempt: {failureCount + 1})
315 </span>
316 ) : (
317 <span> </span>
318 )}
319 </div>
320 </>
321 )}
322 </div>
323 );
324}
325β
326function AddTodo() {
327 const [name, setName] = React.useState("");
328β
329 const [mutate, { status, error }] = useMutation(postTodo, {
330 onSuccess: () => {
331 queryCache.refetchQueries("todos");
332 }
333 });
334β
335 return (
336 <div>
337 <input
338 value={name}
339 onChange={e => setName(e.target.value)}
340 disabled={status === "loading"}
341 />
342 <button
343 onClick={() => mutate({ name })}
344 disabled={status === "loading" || !name}
345 >
346 Add Todo
347 </button>
348 <div>
349 {status === "loading"
350 ? "Saving..."
351 : status === "error"
352 ? error.message
353 : "Saved!"}
354 </div>
355 </div>
356 );
357}
358β
359function fetchTodos(key, { filter } = {}) {
360 console.info("fetchTodos", { filter });
361 const promise = new Promise((resolve, reject) => {
362 setTimeout(() => {
363 if (Math.random() < errorRate) {
364 return reject(
365 new Error(JSON.stringify({ fetchTodos: { filter } }, null, 2))
366 );
367 }
368 resolve(list.filter(d => d.name.includes(filter)));
369 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
370 });
371β
372 promise.cancel = () => console.info("cancelled", filter);
373β
374 return promise;
375}
376β
377function fetchTodoById(key, { id }) {
378 console.info("fetchTodoById", { id });
379 return new Promise((resolve, reject) => {
380 setTimeout(() => {
381 if (Math.random() < errorRate) {
382 return reject(
383 new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2))
384 );
385 }
386 resolve(list.find(d => d.id == id));
387 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
388 });
389}
390β
391function postTodo({ name, notes }) {
392 console.info("postTodo", { name, notes });
393 return new Promise((resolve, reject) => {
394 setTimeout(() => {
395 if (Math.random() < errorRate) {
396 return reject(
397 new Error(JSON.stringify({ postTodo: { name, notes } }, null, 2))
398 );
399 }
400 const todo = { name, notes, id: id++ };
401 list = [...list, todo];
402 resolve(todo);
403 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
404 });
405}
406β
407function patchTodo(todo) {
408 console.info("patchTodo", todo);
409 return new Promise((resolve, reject) => {
410 setTimeout(() => {
411 if (Math.random() < errorRate) {
412 return reject(new Error(JSON.stringify({ patchTodo: todo }, null, 2)));
413 }
414 list = list.map(d => {
415 if (d.id === todo.id) {
416 return todo;
417 }
418 return d;
419 });
420 resolve(todo);
421 }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
422 });
423}
424β
425const rootElement = document.getElementById("root");
426ReactDOM.render(<Root />, rootElement);