-
-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
routes.tsx
400 lines (359 loc) · 9.64 KB
/
routes.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import React from "react";
import {
Await,
Form,
Link,
Outlet,
defer,
useAsyncError,
useAsyncValue,
useFetcher,
useFetchers,
useLoaderData,
useNavigation,
useParams,
useRevalidator,
useRouteError,
json,
useActionData,
ActionFunctionArgs,
LoaderFunctionArgs,
} from "react-router-dom";
import type { Todos } from "./todos";
import { addTodo, deleteTodo, getTodos } from "./todos";
export function sleep(n: number = 500) {
return new Promise((r) => setTimeout(r, n));
}
export function Fallback() {
return <p>Performing initial data "load"</p>;
}
// Layout
export function Layout() {
let navigation = useNavigation();
let { revalidate } = useRevalidator();
let fetchers = useFetchers();
let fetcherInProgress = fetchers.some((f) =>
["loading", "submitting"].includes(f.state)
);
return (
<>
<nav>
<Link to="/">Home</Link>
|
<Link to="/todos">Todos</Link>
|
<Link to="/deferred">Deferred</Link>
|
<Link to="/deferred/child">Deferred Child</Link>
|
<Link to="/await">Await</Link>
|
<Link to="/long-load">Long Load</Link>
|
<Link to="/404">404 Link</Link>
<button onClick={() => revalidate()}>Revalidate</button>
</nav>
<div style={{ position: "fixed", top: 0, right: 0 }}>
{navigation.state !== "idle" && <p>Navigation in progress...</p>}
{fetcherInProgress && <p>Fetcher in progress...</p>}
</div>
<p>
Click on over to <Link to="/todos">/todos</Link> and check out these
data loading APIs!{" "}
</p>
<p>
Or, checkout <Link to="/deferred">/deferred</Link> to see how to
separate critical and lazily loaded data in your loaders.
</p>
<p>
We've introduced some fake async-aspects of routing here, so Keep an eye
on the top-right hand corner to see when we're actively navigating.
</p>
<Outlet />
</>
);
}
// Home
interface HomeLoaderData {
date: string;
}
export async function homeLoader(): Promise<HomeLoaderData> {
await sleep();
return {
date: new Date().toISOString(),
};
}
export function Home() {
let data = useLoaderData() as HomeLoaderData;
return (
<>
<h2>Home</h2>
<p>Last loaded at: {data.date}</p>
</>
);
}
// Todos
export async function todosAction({ request }: ActionFunctionArgs) {
await sleep();
let formData = await request.formData();
// Deletion via fetcher
if (formData.get("action") === "delete") {
let id = formData.get("todoId");
if (typeof id === "string") {
deleteTodo(id);
return { ok: true };
}
}
// Addition via <Form>
let todo = formData.get("todo");
if (typeof todo === "string") {
addTodo(todo);
}
return new Response(null, {
status: 302,
headers: { Location: "/todos" },
});
}
export async function todosLoader(): Promise<Todos> {
await sleep();
return getTodos();
}
export function TodosList() {
let todos = useLoaderData() as Todos;
let navigation = useNavigation();
let formRef = React.useRef<HTMLFormElement>(null);
// If we add and then we delete - this will keep isAdding=true until the
// fetcher completes it's revalidation
let [isAdding, setIsAdding] = React.useState(false);
React.useEffect(() => {
if (navigation.formData?.get("action") === "add") {
setIsAdding(true);
} else if (navigation.state === "idle") {
setIsAdding(false);
formRef.current?.reset();
}
}, [navigation]);
return (
<>
<h2>Todos</h2>
<p>
This todo app uses a <Form> to submit new todos and a
<fetcher.form> to delete todos. Click on a todo item to navigate
to the /todos/:id route.
</p>
<ul>
<li>
<Link to="/todos/junk">
Click this link to force an error in the loader
</Link>
</li>
{Object.entries(todos).map(([id, todo]) => (
<li key={id}>
<TodoItem id={id} todo={todo} />
</li>
))}
</ul>
<Form method="post" ref={formRef}>
<input type="hidden" name="action" value="add" />
<input name="todo"></input>
<button type="submit" disabled={isAdding}>
{isAdding ? "Adding..." : "Add"}
</button>
</Form>
<Outlet />
</>
);
}
export function TodosBoundary() {
let error = useRouteError() as Error;
return (
<>
<h2>Error 💥</h2>
<p>{error.message}</p>
</>
);
}
interface TodoItemProps {
id: string;
todo: string;
}
export function TodoItem({ id, todo }: TodoItemProps) {
let fetcher = useFetcher();
let isDeleting = fetcher.formData != null;
return (
<>
<Link to={`/todos/${id}`}>{todo}</Link>
<fetcher.Form method="post" style={{ display: "inline" }}>
<input type="hidden" name="action" value="delete" />
<button type="submit" name="todoId" value={id} disabled={isDeleting}>
{isDeleting ? "Deleting..." : "Delete"}
</button>
</fetcher.Form>
</>
);
}
// Todo
export async function todoLoader({
params,
}: LoaderFunctionArgs): Promise<string> {
await sleep();
let todos = getTodos();
if (!params.id) {
throw new Error("Expected params.id");
}
let todo = todos[params.id];
if (!todo) {
throw new Error(`Uh oh, I couldn't find a todo with id "${params.id}"`);
}
return todo;
}
export function Todo() {
let params = useParams();
let todo = useLoaderData() as string;
return (
<>
<h2>Nested Todo Route:</h2>
<p>id: {params.id}</p>
<p>todo: {todo}</p>
</>
);
}
interface DeferredRouteLoaderData {
critical1: string;
critical2: string;
lazyResolved: Promise<string>;
lazy1: Promise<string>;
lazy2: Promise<string>;
lazy3: Promise<string>;
lazyError: Promise<string>;
}
const rand = () => Math.round(Math.random() * 100);
const resolve = (d: string, ms: number) =>
new Promise((r) => setTimeout(() => r(`${d} - ${rand()}`), ms));
const reject = (d: Error | string, ms: number) =>
new Promise((_, r) =>
setTimeout(() => {
if (d instanceof Error) {
d.message += ` - ${rand()}`;
} else {
d += ` - ${rand()}`;
}
r(d);
}, ms)
);
export async function deferredLoader() {
return defer({
critical1: await resolve("Critical 1", 250),
critical2: await resolve("Critical 2", 500),
lazyResolved: Promise.resolve("Lazy Data immediately resolved - " + rand()),
lazy1: resolve("Lazy 1", 1000),
lazy2: resolve("Lazy 2", 1500),
lazy3: resolve("Lazy 3", 2000),
lazyError: reject(new Error("Kaboom!"), 2500),
});
}
export function DeferredPage() {
let data = useLoaderData() as DeferredRouteLoaderData;
return (
<div>
<p>{data.critical1}</p>
<p>{data.critical2}</p>
<React.Suspense fallback={<p>should not see me!</p>}>
<Await resolve={data.lazyResolved}>
<RenderAwaitedData />
</Await>
</React.Suspense>
<React.Suspense fallback={<p>loading 1...</p>}>
<Await resolve={data.lazy1}>
<RenderAwaitedData />
</Await>
</React.Suspense>
<React.Suspense fallback={<p>loading 2...</p>}>
<Await resolve={data.lazy2}>
<RenderAwaitedData />
</Await>
</React.Suspense>
<React.Suspense fallback={<p>loading 3...</p>}>
<Await resolve={data.lazy3}>{(data: string) => <p>{data}</p>}</Await>
</React.Suspense>
<React.Suspense fallback={<p>loading (error)...</p>}>
<Await resolve={data.lazyError} errorElement={<RenderAwaitedError />}>
<RenderAwaitedData />
</Await>
</React.Suspense>
<Outlet />
</div>
);
}
interface DeferredChildLoaderData {
critical: string;
lazy: Promise<string>;
}
export async function deferredChildLoader() {
return defer({
critical: await resolve("Critical Child Data", 500),
lazy: resolve("Lazy Child Data", 1000),
});
}
export async function deferredChildAction() {
return json({ ok: true });
}
export function DeferredChild() {
let data = useLoaderData() as DeferredChildLoaderData;
let actionData = useActionData();
return (
<div>
<p>{data.critical}</p>
<React.Suspense fallback={<p>loading child...</p>}>
<Await resolve={data.lazy}>
<RenderAwaitedData />
</Await>
</React.Suspense>
<Form method="post">
<button type="submit" name="key" value="value">
Submit
</button>
</Form>
{actionData ? <p>Action data:{JSON.stringify(actionData)}</p> : null}
</div>
);
}
let shouldResolve = true;
let rawPromiseResolver: ((value: unknown) => void) | null;
let rawPromiseRejecter: ((value: unknown) => void) | null;
let rawPromise: Promise<unknown> = new Promise((r, j) => {
rawPromiseResolver = r;
rawPromiseRejecter = j;
});
export function AwaitPage() {
React.useEffect(() => {
setTimeout(() => {
if (shouldResolve) {
rawPromiseResolver?.("Resolved raw promise!");
} else {
rawPromiseRejecter?.("Rejected raw promise!");
}
}, 1000);
}, []);
return (
<React.Suspense fallback={<p>Awaiting raw promise </p>}>
<Await resolve={rawPromise}>{(data: string) => <p>{data}</p>}</Await>
</React.Suspense>
);
}
function RenderAwaitedData() {
let data = useAsyncValue() as string;
return <p>{data}</p>;
}
function RenderAwaitedError() {
let error = useAsyncError() as Error;
return (
<p style={{ color: "red" }}>
Error (errorElement)!
<br />
{error.message} {error.stack}
</p>
);
}