Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.jsx

441 lines11.1 KB

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