/
hooks.tsx
805 lines (719 loc) · 24.3 KB
/
hooks.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
import * as React from "react";
import type {
Location,
ParamParseKey,
Params,
Path,
PathMatch,
PathPattern,
Router as RemixRouter,
To,
} from "@remix-run/router";
import {
Action as NavigationType,
invariant,
isRouteErrorResponse,
joinPaths,
matchPath,
matchRoutes,
parsePath,
resolveTo,
warning,
UNSAFE_getPathContributingMatches as getPathContributingMatches,
} from "@remix-run/router";
import type {
NavigateOptions,
RouteContextObject,
RouteMatch,
RouteObject,
DataRouteMatch,
RelativeRoutingType,
} from "./context";
import {
DataRouterContext,
DataRouterStateContext,
LocationContext,
NavigationContext,
RouteContext,
RouteErrorContext,
AwaitContext,
DataStaticRouterContext,
} from "./context";
/**
* Returns the full href for the given "to" value. This is useful for building
* custom links that are also accessible and preserve right-click behavior.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-href
*/
export function useHref(
to: To,
{ relative }: { relative?: RelativeRoutingType } = {}
): string {
invariant(
useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useHref() may be used only in the context of a <Router> component.`
);
let { basename, navigator } = React.useContext(NavigationContext);
let { hash, pathname, search } = useResolvedPath(to, { relative });
let joinedPathname = pathname;
// If we're operating within a basename, prepend it to the pathname prior
// to creating the href. If this is a root navigation, then just use the raw
// basename which allows the basename to have full control over the presence
// of a trailing slash on root links
if (basename !== "/") {
joinedPathname =
pathname === "/" ? basename : joinPaths([basename, pathname]);
}
return navigator.createHref({ pathname: joinedPathname, search, hash });
}
/**
* Returns true if this component is a descendant of a <Router>.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-in-router-context
*/
export function useInRouterContext(): boolean {
return React.useContext(LocationContext) != null;
}
/**
* Returns the current location object, which represents the current URL in web
* browsers.
*
* Note: If you're using this it may mean you're doing some of your own
* "routing" in your app, and we'd like to know what your use case is. We may
* be able to provide something higher-level to better suit your needs.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-location
*/
export function useLocation(): Location {
invariant(
useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useLocation() may be used only in the context of a <Router> component.`
);
return React.useContext(LocationContext).location;
}
/**
* Returns the current navigation action which describes how the router came to
* the current location, either by a pop, push, or replace on the history stack.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-navigation-type
*/
export function useNavigationType(): NavigationType {
return React.useContext(LocationContext).navigationType;
}
/**
* Returns true if the URL for the given "to" value matches the current URL.
* This is useful for components that need to know "active" state, e.g.
* <NavLink>.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-match
*/
export function useMatch<
ParamKey extends ParamParseKey<Path>,
Path extends string
>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {
invariant(
useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useMatch() may be used only in the context of a <Router> component.`
);
let { pathname } = useLocation();
return React.useMemo(
() => matchPath<ParamKey, Path>(pattern, pathname),
[pathname, pattern]
);
}
/**
* The interface for the navigate() function returned from useNavigate().
*/
export interface NavigateFunction {
(to: To, options?: NavigateOptions): void;
(delta: number): void;
}
/**
* Returns an imperative method for changing the location. Used by <Link>s, but
* may also be used by other elements to change the location.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-navigate
*/
export function useNavigate(): NavigateFunction {
invariant(
useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useNavigate() may be used only in the context of a <Router> component.`
);
let { basename, navigator } = React.useContext(NavigationContext);
let { matches } = React.useContext(RouteContext);
let { pathname: locationPathname } = useLocation();
let routePathnamesJson = JSON.stringify(
getPathContributingMatches(matches).map((match) => match.pathnameBase)
);
let activeRef = React.useRef(false);
React.useEffect(() => {
activeRef.current = true;
});
let navigate: NavigateFunction = React.useCallback(
(to: To | number, options: NavigateOptions = {}) => {
warning(
activeRef.current,
`You should call navigate() in a React.useEffect(), not when ` +
`your component is first rendered.`
);
if (!activeRef.current) return;
if (typeof to === "number") {
navigator.go(to);
return;
}
let path = resolveTo(
to,
JSON.parse(routePathnamesJson),
locationPathname,
options.relative === "path"
);
// If we're operating within a basename, prepend it to the pathname prior
// to handing off to history. If this is a root navigation, then we
// navigate to the raw basename which allows the basename to have full
// control over the presence of a trailing slash on root links
if (basename !== "/") {
path.pathname =
path.pathname === "/"
? basename
: joinPaths([basename, path.pathname]);
}
(!!options.replace ? navigator.replace : navigator.push)(
path,
options.state,
options
);
},
[basename, navigator, routePathnamesJson, locationPathname]
);
return navigate;
}
const OutletContext = React.createContext<unknown>(null);
/**
* Returns the context (if provided) for the child route at this level of the route
* hierarchy.
* @see https://reactrouter.com/docs/en/v6/hooks/use-outlet-context
*/
export function useOutletContext<Context = unknown>(): Context {
return React.useContext(OutletContext) as Context;
}
/**
* Returns the element for the child route at this level of the route
* hierarchy. Used internally by <Outlet> to render child routes.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-outlet
*/
export function useOutlet(context?: unknown): React.ReactElement | null {
let outlet = React.useContext(RouteContext).outlet;
if (outlet) {
return (
<OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>
);
}
return outlet;
}
/**
* Returns an object of key/value pairs of the dynamic params from the current
* URL that were matched by the route path.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-params
*/
export function useParams<
ParamsOrKey extends string | Record<string, string | undefined> = string
>(): Readonly<
[ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>
> {
let { matches } = React.useContext(RouteContext);
let routeMatch = matches[matches.length - 1];
return routeMatch ? (routeMatch.params as any) : {};
}
/**
* Resolves the pathname of the given `to` value against the current location.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-resolved-path
*/
export function useResolvedPath(
to: To,
{ relative }: { relative?: RelativeRoutingType } = {}
): Path {
let { matches } = React.useContext(RouteContext);
let { pathname: locationPathname } = useLocation();
let routePathnamesJson = JSON.stringify(
getPathContributingMatches(matches).map((match) => match.pathnameBase)
);
return React.useMemo(
() =>
resolveTo(
to,
JSON.parse(routePathnamesJson),
locationPathname,
relative === "path"
),
[to, routePathnamesJson, locationPathname, relative]
);
}
/**
* Returns the element of the route that matched the current location, prepared
* with the correct context to render the remainder of the route tree. Route
* elements in the tree must render an <Outlet> to render their child route's
* element.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-routes
*/
export function useRoutes(
routes: RouteObject[],
locationArg?: Partial<Location> | string
): React.ReactElement | null {
invariant(
useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useRoutes() may be used only in the context of a <Router> component.`
);
let dataRouterStateContext = React.useContext(DataRouterStateContext);
let { matches: parentMatches } = React.useContext(RouteContext);
let routeMatch = parentMatches[parentMatches.length - 1];
let parentParams = routeMatch ? routeMatch.params : {};
let parentPathname = routeMatch ? routeMatch.pathname : "/";
let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
let parentRoute = routeMatch && routeMatch.route;
if (__DEV__) {
// You won't get a warning about 2 different <Routes> under a <Route>
// without a trailing *, but this is a best-effort warning anyway since we
// cannot even give the warning unless they land at the parent route.
//
// Example:
//
// <Routes>
// {/* This route path MUST end with /* because otherwise
// it will never match /blog/post/123 */}
// <Route path="blog" element={<Blog />} />
// <Route path="blog/feed" element={<BlogFeed />} />
// </Routes>
//
// function Blog() {
// return (
// <Routes>
// <Route path="post/:id" element={<Post />} />
// </Routes>
// );
// }
let parentPath = (parentRoute && parentRoute.path) || "";
warningOnce(
parentPathname,
!parentRoute || parentPath.endsWith("*"),
`You rendered descendant <Routes> (or called \`useRoutes()\`) at ` +
`"${parentPathname}" (under <Route path="${parentPath}">) but the ` +
`parent route path has no trailing "*". This means if you navigate ` +
`deeper, the parent won't match anymore and therefore the child ` +
`routes will never render.\n\n` +
`Please change the parent <Route path="${parentPath}"> to <Route ` +
`path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
);
}
let locationFromContext = useLocation();
let location;
if (locationArg) {
let parsedLocationArg =
typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
invariant(
parentPathnameBase === "/" ||
parsedLocationArg.pathname?.startsWith(parentPathnameBase),
`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, ` +
`the location pathname must begin with the portion of the URL pathname that was ` +
`matched by all parent routes. The current pathname base is "${parentPathnameBase}" ` +
`but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`
);
location = parsedLocationArg;
} else {
location = locationFromContext;
}
let pathname = location.pathname || "/";
let remainingPathname =
parentPathnameBase === "/"
? pathname
: pathname.slice(parentPathnameBase.length) || "/";
let matches = matchRoutes(routes, { pathname: remainingPathname });
if (__DEV__) {
warning(
parentRoute || matches != null,
`No routes matched location "${location.pathname}${location.search}${location.hash}" `
);
warning(
matches == null ||
matches[matches.length - 1].route.element !== undefined,
`Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element. ` +
`This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`
);
}
let renderedMatches = _renderMatches(
matches &&
matches.map((match) =>
Object.assign({}, match, {
params: Object.assign({}, parentParams, match.params),
pathname: joinPaths([parentPathnameBase, match.pathname]),
pathnameBase:
match.pathnameBase === "/"
? parentPathnameBase
: joinPaths([parentPathnameBase, match.pathnameBase]),
})
),
parentMatches,
dataRouterStateContext || undefined
);
// When a user passes in a `locationArg`, the associated routes need to
// be wrapped in a new `LocationContext.Provider` in order for `useLocation`
// to use the scoped location instead of the global location.
if (locationArg) {
return (
<LocationContext.Provider
value={{
location: {
pathname: "/",
search: "",
hash: "",
state: null,
key: "default",
...location,
},
navigationType: NavigationType.Pop,
}}
>
{renderedMatches}
</LocationContext.Provider>
);
}
return renderedMatches;
}
function DefaultErrorElement() {
let error = useRouteError();
let message = isRouteErrorResponse(error)
? `${error.status} ${error.statusText}`
: error instanceof Error
? error.message
: JSON.stringify(error);
let stack = error instanceof Error ? error.stack : null;
let lightgrey = "rgba(200,200,200, 0.5)";
let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
return (
<>
<h2>Unhandled Thrown Error!</h2>
<h3 style={{ fontStyle: "italic" }}>{message}</h3>
{stack ? <pre style={preStyles}>{stack}</pre> : null}
<p>💿 Hey developer 👋</p>
<p>
You can provide a way better UX than this when your app throws errors by
providing your own
<code style={codeStyles}>errorElement</code> props on
<code style={codeStyles}><Route></code>
</p>
</>
);
}
type RenderErrorBoundaryProps = React.PropsWithChildren<{
location: Location;
error: any;
component: React.ReactNode;
}>;
type RenderErrorBoundaryState = {
location: Location;
error: any;
};
export class RenderErrorBoundary extends React.Component<
RenderErrorBoundaryProps,
RenderErrorBoundaryState
> {
constructor(props: RenderErrorBoundaryProps) {
super(props);
this.state = {
location: props.location,
error: props.error,
};
}
static getDerivedStateFromError(error: any) {
return { error: error };
}
static getDerivedStateFromProps(
props: RenderErrorBoundaryProps,
state: RenderErrorBoundaryState
) {
// When we get into an error state, the user will likely click "back" to the
// previous page that didn't have an error. Because this wraps the entire
// application, that will have no effect--the error page continues to display.
// This gives us a mechanism to recover from the error when the location changes.
//
// Whether we're in an error state or not, we update the location in state
// so that when we are in an error state, it gets reset when a new location
// comes in and the user recovers from the error.
if (state.location !== props.location) {
return {
error: props.error,
location: props.location,
};
}
// If we're not changing locations, preserve the location but still surface
// any new errors that may come through. We retain the existing error, we do
// this because the error provided from the app state may be cleared without
// the location changing.
return {
error: props.error || state.error,
location: state.location,
};
}
componentDidCatch(error: any, errorInfo: any) {
console.error(
"React Router caught the following error during render",
error,
errorInfo
);
}
render() {
return this.state.error ? (
<RouteErrorContext.Provider
value={this.state.error}
children={this.props.component}
/>
) : (
this.props.children
);
}
}
interface RenderedRouteProps {
routeContext: RouteContextObject;
match: RouteMatch<string, RouteObject>;
children: React.ReactNode | null;
}
function RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {
let dataStaticRouterContext = React.useContext(DataStaticRouterContext);
// Track how deep we got in our render pass to emulate SSR componentDidCatch
// in a DataStaticRouter
if (dataStaticRouterContext && match.route.errorElement) {
dataStaticRouterContext._deepestRenderedBoundaryId = match.route.id;
}
return (
<RouteContext.Provider value={routeContext}>
{children}
</RouteContext.Provider>
);
}
export function _renderMatches(
matches: RouteMatch[] | null,
parentMatches: RouteMatch[] = [],
dataRouterState?: RemixRouter["state"]
): React.ReactElement | null {
if (matches == null) {
if (dataRouterState?.errors) {
// Don't bail if we have data router errors so we can render them in the
// boundary. Use the pre-matched (or shimmed) matches
matches = dataRouterState.matches as DataRouteMatch[];
} else {
return null;
}
}
let renderedMatches = matches;
// If we have data errors, trim matches to the highest error boundary
let errors = dataRouterState?.errors;
if (errors != null) {
let errorIndex = renderedMatches.findIndex(
(m) => m.route.id && errors?.[m.route.id]
);
invariant(
errorIndex >= 0,
`Could not find a matching route for the current errors: ${errors}`
);
renderedMatches = renderedMatches.slice(
0,
Math.min(renderedMatches.length, errorIndex + 1)
);
}
return renderedMatches.reduceRight((outlet, match, index) => {
let error = match.route.id ? errors?.[match.route.id] : null;
// Only data routers handle errors
let errorElement = dataRouterState
? match.route.errorElement || <DefaultErrorElement />
: null;
let getChildren = () => (
<RenderedRoute
match={match}
routeContext={{
outlet,
matches: parentMatches.concat(renderedMatches.slice(0, index + 1)),
}}
>
{error
? errorElement
: match.route.element !== undefined
? match.route.element
: outlet}
</RenderedRoute>
);
// Only wrap in an error boundary within data router usages when we have an
// errorElement on this route. Otherwise let it bubble up to an ancestor
// errorElement
return dataRouterState && (match.route.errorElement || index === 0) ? (
<RenderErrorBoundary
location={dataRouterState.location}
component={errorElement}
error={error}
children={getChildren()}
/>
) : (
getChildren()
);
}, null as React.ReactElement | null);
}
enum DataRouterHook {
UseRevalidator = "useRevalidator",
}
enum DataRouterStateHook {
UseLoaderData = "useLoaderData",
UseActionData = "useActionData",
UseRouteError = "useRouteError",
UseNavigation = "useNavigation",
UseRouteLoaderData = "useRouteLoaderData",
UseMatches = "useMatches",
UseRevalidator = "useRevalidator",
}
function getDataRouterConsoleError(
hookName: DataRouterHook | DataRouterStateHook
) {
return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
}
function useDataRouterContext(hookName: DataRouterHook) {
let ctx = React.useContext(DataRouterContext);
invariant(ctx, getDataRouterConsoleError(hookName));
return ctx;
}
function useDataRouterState(hookName: DataRouterStateHook) {
let state = React.useContext(DataRouterStateContext);
invariant(state, getDataRouterConsoleError(hookName));
return state;
}
/**
* Returns the current navigation, defaulting to an "idle" navigation when
* no navigation is in progress
*/
export function useNavigation() {
let state = useDataRouterState(DataRouterStateHook.UseNavigation);
return state.navigation;
}
/**
* Returns a revalidate function for manually triggering revalidation, as well
* as the current state of any manual revalidations
*/
export function useRevalidator() {
let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
return {
revalidate: dataRouterContext.router.revalidate,
state: state.revalidation,
};
}
/**
* Returns the active route matches, useful for accessing loaderData for
* parent/child routes or the route "handle" property
*/
export function useMatches() {
let { matches, loaderData } = useDataRouterState(
DataRouterStateHook.UseMatches
);
return React.useMemo(
() =>
matches.map((match) => {
let { pathname, params } = match;
// Note: This structure matches that created by createUseMatchesMatch
// in the @remix-run/router , so if you change this please also change
// that :) Eventually we'll DRY this up
return {
id: match.route.id,
pathname,
params,
data: loaderData[match.route.id] as unknown,
handle: match.route.handle as unknown,
};
}),
[matches, loaderData]
);
}
/**
* Returns the loader data for the nearest ancestor Route loader
*/
export function useLoaderData(): unknown {
let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
let route = React.useContext(RouteContext);
invariant(route, `useLoaderData must be used inside a RouteContext`);
let thisRoute = route.matches[route.matches.length - 1];
invariant(
thisRoute.route.id,
`useLoaderData can only be used on routes that contain a unique "id"`
);
return state.loaderData[thisRoute.route.id];
}
/**
* Returns the loaderData for the given routeId
*/
export function useRouteLoaderData(routeId: string): unknown {
let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
return state.loaderData[routeId];
}
/**
* Returns the action data for the nearest ancestor Route action
*/
export function useActionData(): unknown {
let state = useDataRouterState(DataRouterStateHook.UseActionData);
let route = React.useContext(RouteContext);
invariant(route, `useActionData must be used inside a RouteContext`);
return Object.values(state?.actionData || {})[0];
}
/**
* Returns the nearest ancestor Route error, which could be a loader/action
* error or a render error. This is intended to be called from your
* errorElement to display a proper error message.
*/
export function useRouteError(): unknown {
let error = React.useContext(RouteErrorContext);
let state = useDataRouterState(DataRouterStateHook.UseRouteError);
let route = React.useContext(RouteContext);
let thisRoute = route.matches[route.matches.length - 1];
// If this was a render error, we put it in a RouteError context inside
// of RenderErrorBoundary
if (error) {
return error;
}
invariant(route, `useRouteError must be used inside a RouteContext`);
invariant(
thisRoute.route.id,
`useRouteError can only be used on routes that contain a unique "id"`
);
// Otherwise look for errors from our data router state
return state.errors?.[thisRoute.route.id];
}
/**
* Returns the happy-path data from the nearest ancestor <Await /> value
*/
export function useAsyncValue(): unknown {
let value = React.useContext(AwaitContext);
return value?._data;
}
/**
* Returns the error from the nearest ancestor <Await /> value
*/
export function useAsyncError(): unknown {
let value = React.useContext(AwaitContext);
return value?._error;
}
const alreadyWarned: Record<string, boolean> = {};
function warningOnce(key: string, cond: boolean, message: string) {
if (!cond && !alreadyWarned[key]) {
alreadyWarned[key] = true;
warning(false, message);
}
}