UNPKG

32.5 kB TypeScript View Raw
1
2import { Action, Location, Path, To } from "./router/history.js";
3import { ParamParseKey, Params, PathMatch, PathPattern, RouteObject, UIMatch } from "./router/utils.js";
4import { Blocker, BlockerFunction, NavigationStates, RelativeRoutingType, Router } from "./router/router.js";
5import { NavigateOptions } from "./context.js";
6import { GetActionData, GetLoaderData, SerializeFrom } from "./types/route-data.js";
7import { RouteModules } from "./types/register.js";
8import * as React$1 from "react";
9
10//#region lib/hooks.d.ts
11/**
12 * Resolves a URL against the current {@link Location}.
13 *
14 * @example
15 * import { useHref } from "react-router";
16 *
17 * function SomeComponent() {
18 * let href = useHref("some/where");
19 * // "/resolved/some/where"
20 * }
21 *
22 * @public
23 * @category Hooks
24 * @param to The path to resolve
25 * @param options Options
26 * @param options.relative Defaults to `"route"` so routing is relative to the
27 * route tree.
28 * Set to `"path"` to make relative routing operate against path segments.
29 * @returns The resolved href string
30 */
31declare function useHref(to: To, {
32 relative
33}?: {
34 relative?: RelativeRoutingType;
35}): string;
36/**
37 * Returns `true` if this component is a descendant of a {@link Router}, useful
38 * to ensure a component is used within a {@link Router}.
39 *
40 * @public
41 * @category Hooks
42 * @mode framework
43 * @mode data
44 * @returns Whether the component is within a {@link Router} context
45 */
46declare function useInRouterContext(): boolean;
47/**
48 * Returns the current {@link Location}. This can be useful if you'd like to
49 * perform some side effect whenever it changes.
50 *
51 * @example
52 * import * as React from 'react'
53 * import { useLocation } from 'react-router'
54 *
55 * function SomeComponent() {
56 * let location = useLocation()
57 *
58 * React.useEffect(() => {
59 * // Google Analytics
60 * ga('send', 'pageview')
61 * }, [location]);
62 *
63 * return (
64 * // ...
65 * );
66 * }
67 *
68 * @public
69 * @category Hooks
70 * @returns The current {@link Location} object
71 */
72declare function useLocation(): Location;
73/**
74 * Returns the current {@link Navigation} action which describes how the router
75 * came to the current {@link Location}, either by a pop, push, or replace on
76 * the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack.
77 *
78 * @public
79 * @category Hooks
80 * @returns The current {@link NavigationType} (`"POP"`, `"PUSH"`, or `"REPLACE"`)
81 */
82declare function useNavigationType(): Action;
83/**
84 * Returns a {@link PathMatch} object if the given pattern matches the current URL.
85 * This is useful for components that need to know "active" state, e.g.
86 * {@link NavLink | `<NavLink>`}.
87 *
88 * @public
89 * @category Hooks
90 * @param pattern The pattern to match against the current {@link Location}
91 * @returns The path match object if the pattern matches, `null` otherwise
92 */
93declare function useMatch<Path extends string>(pattern: PathPattern<Path> | Path): PathMatch<ParamParseKey<Path>> | null;
94/**
95 * The interface for the `navigate` function returned from {@link useNavigate}.
96 */
97interface NavigateFunction {
98 (to: To, options?: NavigateOptions): void | Promise<void>;
99 (delta: number): void | Promise<void>;
100}
101/**
102 * Returns a function that lets you navigate programmatically in the browser in
103 * response to user interactions or effects.
104 *
105 * It's often better to use {@link redirect} in [`action`](../../start/framework/route-module#action)/[`loader`](../../start/framework/route-module#loader)
106 * functions than this hook.
107 *
108 * The returned function signature is `navigate(to, options?)`/`navigate(delta)` where:
109 *
110 * * `to` can be a string path, a {@link To} object, or a number (delta)
111 * * `options` contains options for modifying the navigation
112 * * These options work in all modes (Framework, Data, and Declarative):
113 * * `relative`: `"route"` or `"path"` to control relative routing logic
114 * * `replace`: Replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack
115 * * `state`: Optional [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state) to include with the new {@link Location}
116 * * These options only work in Framework and Data modes:
117 * * `flushSync`: Wrap the DOM updates in [`ReactDom.flushSync`](https://react.dev/reference/react-dom/flushSync)
118 * * `preventScrollReset`: Do not scroll back to the top of the page after navigation
119 * * `viewTransition`: **Deprecated.** Use React's [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) component instead. See the [migration guide](../../how-to/view-transitions).
120 *
121 * @example
122 * import { useNavigate } from "react-router";
123 *
124 * function SomeComponent() {
125 * let navigate = useNavigate();
126 * return (
127 * <button onClick={() => navigate(-1)}>
128 * Go Back
129 * </button>
130 * );
131 * }
132 *
133 * @additionalExamples
134 * ### Navigate to another path
135 *
136 * ```tsx
137 * navigate("/some/route");
138 * navigate("/some/route?search=param");
139 * ```
140 *
141 * ### Navigate with a {@link To} object
142 *
143 * All properties are optional.
144 *
145 * ```tsx
146 * navigate(
147 * {
148 * pathname: "/some/route",
149 * search: "?search=param",
150 * hash: "#hash",
151 * },
152 * {
153 * state: { some: "state" },
154 * },
155 * );
156 * ```
157 *
158 * If you use `state`, that will be available on the {@link Location} object on
159 * the next page. Access it with `useLocation().state` (see {@link useLocation}).
160 *
161 * ### Navigate back or forward in the history stack
162 *
163 * ```tsx
164 * // back
165 * // often used to close modals
166 * navigate(-1);
167 *
168 * // forward
169 * // often used in a multistep wizard workflows
170 * navigate(1);
171 * ```
172 *
173 * Be cautious with `navigate(number)`. If your application can load up to a
174 * route that has a button that tries to navigate forward/back, there may not be
175 * a [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
176 * entry to go back or forward to, or it can go somewhere you don't expect
177 * (like a different domain).
178 *
179 * Only use this if you're sure they will have an entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
180 * stack to navigate to.
181 *
182 * ### Replace the current entry in the history stack
183 *
184 * This will remove the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
185 * stack, replacing it with a new one, similar to a server side redirect.
186 *
187 * ```tsx
188 * navigate("/some/route", { replace: true });
189 * ```
190 *
191 * ### Prevent Scroll Reset
192 *
193 * [MODES: framework, data]
194 *
195 * To prevent {@link ScrollRestoration | `<ScrollRestoration>`} from resetting
196 * the scroll position, use the `preventScrollReset` option.
197 *
198 * ```tsx
199 * navigate("?some-tab=1", { preventScrollReset: true });
200 * ```
201 *
202 * For example, if you have a tab interface connected to search params in the
203 * middle of a page, and you don't want it to scroll to the top when a tab is
204 * clicked.
205 *
206 * ### Return Type Augmentation
207 *
208 * Internally, `useNavigate` uses a separate implementation when you are in
209 * Declarative mode versus Data/Framework mode - the primary difference being
210 * that the latter is able to return a stable reference that does not change
211 * identity across navigations. The implementation in Data/Framework mode also
212 * returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
213 * that resolves when the navigation is completed. This means the return type of
214 * `useNavigate` is `void | Promise<void>`. This is accurate, but can lead to
215 * some red squigglies based on the union in the return value:
216 *
217 * - If you're using `typescript-eslint`, you may see errors from
218 * [`@typescript-eslint/no-floating-promises`](https://typescript-eslint.io/rules/no-floating-promises)
219 * - In Framework/Data mode, `React.use(navigate())` will show a false-positive
220 * `Argument of type 'void | Promise<void>' is not assignable to parameter of
221 * type 'Usable<void>'` error
222 *
223 * The easiest way to work around these issues is to augment the type based on the
224 * router you're using:
225 *
226 * ```ts
227 * // If using <BrowserRouter>
228 * declare module "react-router" {
229 * interface NavigateFunction {
230 * (to: To, options?: NavigateOptions): void;
231 * (delta: number): void;
232 * }
233 * }
234 *
235 * // If using <RouterProvider> or Framework mode
236 * declare module "react-router" {
237 * interface NavigateFunction {
238 * (to: To, options?: NavigateOptions): Promise<void>;
239 * (delta: number): Promise<void>;
240 * }
241 * }
242 * ```
243 *
244 * @public
245 * @category Hooks
246 * @returns A navigate function for programmatic navigation
247 */
248declare function useNavigate(): NavigateFunction;
249/**
250 * Returns the parent route {@link Outlet | `<Outlet context>`}.
251 *
252 * Often parent routes manage state or other values you want shared with child
253 * routes. You can create your own [context provider](https://react.dev/learn/passing-data-deeply-with-context)
254 * if you like, but this is such a common situation that it's built-into
255 * {@link Outlet | `<Outlet>`}.
256 *
257 * ```tsx
258 * // Parent route
259 * function Parent() {
260 * const [count, setCount] = React.useState(0);
261 * return <Outlet context={[count, setCount]} />;
262 * }
263 * ```
264 *
265 * ```tsx
266 * // Child route
267 * import { useOutletContext } from "react-router";
268 *
269 * function Child() {
270 * const [count, setCount] = useOutletContext();
271 * const increment = () => setCount((c) => c + 1);
272 * return <button onClick={increment}>{count}</button>;
273 * }
274 * ```
275 *
276 * If you're using TypeScript, we recommend the parent component provide a
277 * custom hook for accessing the context value. This makes it easier for
278 * consumers to get nice typings, control consumers, and know who's consuming
279 * the context value.
280 *
281 * Here's a more realistic example:
282 *
283 * ```tsx filename=src/routes/dashboard.tsx lines=[14,20]
284 * import { useState } from "react";
285 * import { Outlet, useOutletContext } from "react-router";
286 *
287 * import type { User } from "./types";
288 *
289 * type ContextType = { user: User | null };
290 *
291 * export default function Dashboard() {
292 * const [user, setUser] = useState<User | null>(null);
293 *
294 * return (
295 * <div>
296 * <h1>Dashboard</h1>
297 * <Outlet context={{ user } satisfies ContextType} />
298 * </div>
299 * );
300 * }
301 *
302 * export function useUser() {
303 * return useOutletContext<ContextType>();
304 * }
305 * ```
306 *
307 * ```tsx filename=src/routes/dashboard/messages.tsx lines=[1,4]
308 * import { useUser } from "../dashboard";
309 *
310 * export default function DashboardMessages() {
311 * const { user } = useUser();
312 * return (
313 * <div>
314 * <h2>Messages</h2>
315 * <p>Hello, {user.name}!</p>
316 * </div>
317 * );
318 * }
319 * ```
320 *
321 * @public
322 * @category Hooks
323 * @returns The context value passed to the parent {@link Outlet} component
324 */
325declare function useOutletContext<Context = unknown>(): Context;
326/**
327 * Returns the element for the child route at this level of the route
328 * hierarchy. Used internally by {@link Outlet | `<Outlet>`} to render child
329 * routes.
330 *
331 * @public
332 * @category Hooks
333 * @param context The context to pass to the outlet
334 * @returns The child route element or `null` if no child routes match
335 */
336declare function useOutlet(context?: unknown): React$1.ReactElement | null;
337/**
338 * Returns an object of key/value-pairs of the dynamic params from the current
339 * URL that were matched by the routes. Child routes inherit all params from
340 * their parent routes.
341 *
342 * Assuming a route pattern like `/posts/:postId` is matched by `/posts/123`
343 * then `params.postId` will be `"123"`.
344 *
345 * @example
346 * import { useParams } from "react-router";
347 *
348 * function SomeComponent() {
349 * let params = useParams();
350 * params.postId;
351 * }
352 *
353 * @additionalExamples
354 * ### Basic Usage
355 *
356 * ```tsx
357 * import { useParams } from "react-router";
358 *
359 * // given a route like:
360 * <Route path="/posts/:postId" element={<Post />} />;
361 *
362 * // or a data route like:
363 * createBrowserRouter([
364 * {
365 * path: "/posts/:postId",
366 * component: Post,
367 * },
368 * ]);
369 *
370 * // or in routes.ts
371 * route("/posts/:postId", "routes/post.tsx");
372 * ```
373 *
374 * Access the params in a component:
375 *
376 * ```tsx
377 * import { useParams } from "react-router";
378 *
379 * export default function Post() {
380 * let params = useParams();
381 * return <h1>Post: {params.postId}</h1>;
382 * }
383 * ```
384 *
385 * ### Multiple Params
386 *
387 * Patterns can have multiple params:
388 *
389 * ```tsx
390 * "/posts/:postId/comments/:commentId";
391 * ```
392 *
393 * All will be available in the params object:
394 *
395 * ```tsx
396 * import { useParams } from "react-router";
397 *
398 * export default function Post() {
399 * let params = useParams();
400 * return (
401 * <h1>
402 * Post: {params.postId}, Comment: {params.commentId}
403 * </h1>
404 * );
405 * }
406 * ```
407 *
408 * ### Catchall Params
409 *
410 * Catchall params are defined with `*`:
411 *
412 * ```tsx
413 * "/files/*";
414 * ```
415 *
416 * The matched value will be available in the params object as follows:
417 *
418 * ```tsx
419 * import { useParams } from "react-router";
420 *
421 * export default function File() {
422 * let params = useParams();
423 * let catchall = params["*"];
424 * // ...
425 * }
426 * ```
427 *
428 * You can destructure the catchall param:
429 *
430 * ```tsx
431 * export default function File() {
432 * let { "*": catchall } = useParams();
433 * console.log(catchall);
434 * }
435 * ```
436 *
437 * @public
438 * @category Hooks
439 * @returns An object containing the dynamic route parameters
440 */
441declare function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>>;
442/**
443 * Resolves the pathname of the given `to` value against the current
444 * {@link Location}. Similar to {@link useHref}, but returns a
445 * {@link Path} instead of a string.
446 *
447 * @example
448 * import { useResolvedPath } from "react-router";
449 *
450 * function SomeComponent() {
451 * // if the user is at /dashboard/profile
452 * let path = useResolvedPath("../accounts");
453 * path.pathname; // "/dashboard/accounts"
454 * path.search; // ""
455 * path.hash; // ""
456 * }
457 *
458 * @public
459 * @category Hooks
460 * @param to The path to resolve
461 * @param options Options
462 * @param options.relative Defaults to `"route"` so routing is relative to the route tree.
463 * Set to `"path"` to make relative routing operate against path segments.
464 * @returns The resolved {@link Path} object with `pathname`, `search`, and `hash`
465 */
466declare function useResolvedPath(to: To, {
467 relative
468}?: {
469 relative?: RelativeRoutingType;
470}): Path;
471/**
472 * Hook version of {@link Routes | `<Routes>`} that uses objects instead of
473 * components. These objects have the same properties as the component props.
474 * The return value of `useRoutes` is either a valid React element you can use
475 * to render the route tree, or `null` if nothing matched.
476 *
477 * @example
478 * import { useRoutes } from "react-router";
479 *
480 * function App() {
481 * let element = useRoutes([
482 * {
483 * path: "/",
484 * element: <Dashboard />,
485 * children: [
486 * {
487 * path: "messages",
488 * element: <DashboardMessages />,
489 * },
490 * { path: "tasks", element: <DashboardTasks /> },
491 * ],
492 * },
493 * { path: "team", element: <AboutPage /> },
494 * ]);
495 *
496 * return element;
497 * }
498 *
499 * @public
500 * @category Hooks
501 * @param routes An array of {@link RouteObject}s that define the route hierarchy
502 * @param locationArg An optional {@link Location} object or pathname string to
503 * use instead of the current {@link Location}
504 * @returns A React element to render the matched route, or `null` if no routes matched
505 */
506declare function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React$1.ReactElement | null;
507type UseNavigationResult = UseNavigationResultStates[keyof UseNavigationResultStates];
508type UseNavigationResultStates = {
509 Idle: Omit<NavigationStates["Idle"], "matches" | "historyAction">;
510 Loading: Omit<NavigationStates["Loading"], "matches" | "historyAction">;
511 Submitting: Omit<NavigationStates["Submitting"], "matches" | "historyAction">;
512};
513/**
514 * Returns the current {@link Navigation}, defaulting to an "idle" navigation
515 * when no navigation is in progress. You can use this to render pending UI
516 * (like a global spinner) or read [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
517 * from a form navigation.
518 *
519 * @example
520 * import { useNavigation } from "react-router";
521 *
522 * function SomeComponent() {
523 * let navigation = useNavigation();
524 * navigation.state;
525 * navigation.formData;
526 * // etc.
527 * }
528 *
529 * @public
530 * @category Hooks
531 * @mode framework
532 * @mode data
533 * @returns The current {@link Navigation} object
534 */
535declare function useNavigation(): UseNavigationResult;
536/**
537 * Revalidate the data on the page for reasons outside of normal data mutations
538 * like [`Window` focus](https://developer.mozilla.org/en-US/docs/Web/API/Window/focus_event)
539 * or polling on an interval.
540 *
541 * Note that page data is already revalidated automatically after actions.
542 * If you find yourself using this for normal CRUD operations on your data in
543 * response to user interactions, you're probably not taking advantage of the
544 * other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do
545 * this automatically.
546 *
547 * @example
548 * import { useRevalidator } from "react-router";
549 *
550 * function WindowFocusRevalidator() {
551 * const revalidator = useRevalidator();
552 *
553 * useFakeWindowFocus(() => {
554 * revalidator.revalidate();
555 * });
556 *
557 * return (
558 * <div hidden={revalidator.state === "idle"}>
559 * Revalidating...
560 * </div>
561 * );
562 * }
563 *
564 * @public
565 * @category Hooks
566 * @mode framework
567 * @mode data
568 * @returns An object with a `revalidate` function and the current revalidation
569 * `state`
570 */
571declare function useRevalidator(): {
572 revalidate: () => Promise<void>;
573 state: Router["state"]["revalidation"];
574};
575/**
576 * Returns the active route matches, useful for accessing `loaderData` for
577 * parent/child routes or the route [`handle`](../../start/framework/route-module#handle)
578 * property
579 *
580 * Pairing the route `handle` with `useMatches` gets very powerful since you can put
581 * whatever you want on a route handle and have access to `useMatches` anywhere.
582 * Please see the [handle](../../how-to/using-handle) documentation for an example
583 * of breadcrumbs via `useMatches`/`handle`.
584 *
585 * ```tsx
586 * import { useMatches } from "react-router";
587 *
588 * function SomeComponent() {
589 * const matches = useMatches();
590 * // matches[i].id // route id
591 * // matches[i].pathname // the portion of the URL the route matched
592 * // matches[i].params // the parsed params from the URL
593 * // matches[i].loaderData // the data from the loader
594 * // matches[i].handle // the route handle with any app specific data
595 * }
596 * ```
597 *
598 * <docs-info>useMatches only works with a data router like `createBrowserRouter`,
599 * since they know the full route tree up front and can provide all of the current
600 * matches. Additionally, `useMatches` will not match down into any descendant route
601 * trees since the router isn't aware of the descendant routes.</docs-info>
602 *
603 * @public
604 * @category Hooks
605 * @mode framework
606 * @mode data
607 * @returns An array of {@link UIMatch | UI matches} for the current route hierarchy
608 */
609declare function useMatches(): UIMatch[];
610/**
611 * Returns the data from the closest route
612 * [`loader`](../../start/framework/route-module#loader) or
613 * [`clientLoader`](../../start/framework/route-module#clientloader).
614 *
615 * @example
616 * import { useLoaderData } from "react-router";
617 *
618 * export async function loader() {
619 * return await fakeDb.invoices.findAll();
620 * }
621 *
622 * export default function Invoices() {
623 * let invoices = useLoaderData<typeof loader>();
624 * // ...
625 * }
626 *
627 * @public
628 * @category Hooks
629 * @mode framework
630 * @mode data
631 * @returns The data returned from the route's [`loader`](../../start/framework/route-module#loader) or [`clientLoader`](../../start/framework/route-module#clientloader) function
632 */
633declare function useLoaderData<T = any>(): SerializeFrom<T>;
634/**
635 * Returns the [`loader`](../../start/framework/route-module#loader) data for a
636 * given route by route ID.
637 *
638 * Route IDs are created automatically. They are simply the path of the route file
639 * relative to the app folder without the extension.
640 *
641 * | Route Filename | Route ID |
642 * | ---------------------------- | ---------------------- |
643 * | `app/root.tsx` | `"root"` |
644 * | `app/routes/teams.tsx` | `"routes/teams"` |
645 * | `app/whatever/teams.$id.tsx` | `"whatever/teams.$id"` |
646 *
647 * @example
648 * import { useRouteLoaderData } from "react-router";
649 *
650 * function SomeComponent() {
651 * const { user } = useRouteLoaderData("root");
652 * }
653 *
654 * // You can also specify your own route ID's manually in your routes.ts file:
655 * route("/", "containers/app.tsx", { id: "app" })
656 * useRouteLoaderData("app");
657 *
658 * @public
659 * @category Hooks
660 * @mode framework
661 * @mode data
662 * @param routeId The ID of the route to return loader data from
663 * @returns The data returned from the specified route's [`loader`](../../start/framework/route-module#loader)
664 * function, or `undefined` if not found
665 */
666declare function useRouteLoaderData<T = any>(routeId: string): SerializeFrom<T> | undefined;
667/**
668 * Returns the [`action`](../../start/framework/route-module#action) data from
669 * the most recent `POST` navigation form submission or `undefined` if there
670 * hasn't been one.
671 *
672 * @example
673 * import { Form, useActionData } from "react-router";
674 *
675 * export async function action({ request }) {
676 * const body = await request.formData();
677 * const name = body.get("visitorsName");
678 * return { message: `Hello, ${name}` };
679 * }
680 *
681 * export default function Invoices() {
682 * const data = useActionData();
683 * return (
684 * <Form method="post">
685 * <input type="text" name="visitorsName" />
686 * {data ? data.message : "Waiting..."}
687 * </Form>
688 * );
689 * }
690 *
691 * @public
692 * @category Hooks
693 * @mode framework
694 * @mode data
695 * @returns The data returned from the route's [`action`](../../start/framework/route-module#action)
696 * function, or `undefined` if no [`action`](../../start/framework/route-module#action)
697 * has been called
698 */
699declare function useActionData<T = any>(): SerializeFrom<T> | undefined;
700/**
701 * Accesses the error thrown during an
702 * [`action`](../../start/framework/route-module#action),
703 * [`loader`](../../start/framework/route-module#loader),
704 * or component render to be used in a route module
705 * [`ErrorBoundary`](../../start/framework/route-module#errorboundary).
706 *
707 * @example
708 * export function ErrorBoundary() {
709 * const error = useRouteError();
710 * return <div>{error.message}</div>;
711 * }
712 *
713 * @public
714 * @category Hooks
715 * @mode framework
716 * @mode data
717 * @returns The error that was thrown during route [loading](../../start/framework/route-module#loader),
718 * [`action`](../../start/framework/route-module#action) execution, or rendering
719 */
720declare function useRouteError(): unknown;
721/**
722 * Returns the resolved promise value from the closest {@link Await | `<Await>`}.
723 *
724 * @example
725 * function SomeDescendant() {
726 * const value = useAsyncValue();
727 * // ...
728 * }
729 *
730 * // somewhere in your app
731 * <Await resolve={somePromise}>
732 * <SomeDescendant />
733 * </Await>;
734 *
735 * @public
736 * @category Hooks
737 * @mode framework
738 * @mode data
739 * @returns The resolved value from the nearest {@link Await} component
740 */
741declare function useAsyncValue(): unknown;
742/**
743 * Returns the rejection value from the closest {@link Await | `<Await>`}.
744 *
745 * @example
746 * import { Await, useAsyncError } from "react-router";
747 *
748 * function ErrorElement() {
749 * const error = useAsyncError();
750 * return (
751 * <p>Uh Oh, something went wrong! {error.message}</p>
752 * );
753 * }
754 *
755 * // somewhere in your app
756 * <Await
757 * resolve={promiseThatRejects}
758 * errorElement={<ErrorElement />}
759 * />;
760 *
761 * @public
762 * @category Hooks
763 * @mode framework
764 * @mode data
765 * @returns The error that was thrown in the nearest {@link Await} component
766 */
767declare function useAsyncError(): unknown;
768/**
769 * Allow the application to block navigations within the SPA and present the
770 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
771 * using half-filled form data. This does not handle hard-reloads or
772 * cross-origin navigations.
773 *
774 * The {@link Blocker} object returned by the hook has the following properties:
775 *
776 * - **`state`**
777 * - `unblocked` - the blocker is idle and has not prevented any navigation
778 * - `blocked` - the blocker has prevented a navigation
779 * - `proceeding` - the blocker is proceeding through from a blocked navigation
780 * - **`location`**
781 * - When in a `blocked` state, this represents the {@link Location} to which
782 * we blocked a navigation. When in a `proceeding` state, this is the
783 * location being navigated to after a `blocker.proceed()` call.
784 * - **`proceed()`**
785 * - When in a `blocked` state, you may call `blocker.proceed()` to proceed to
786 * the blocked location.
787 * - **`reset()`**
788 * - When in a `blocked` state, you may call `blocker.reset()` to return the
789 * blocker to an `unblocked` state and leave the user at the current
790 * location.
791 *
792 * @example
793 * // Boolean version
794 * let blocker = useBlocker(value !== "");
795 *
796 * // Function version
797 * let blocker = useBlocker(
798 * ({ currentLocation, nextLocation, historyAction }) =>
799 * value !== "" &&
800 * currentLocation.pathname !== nextLocation.pathname
801 * );
802 *
803 * @additionalExamples
804 * ```tsx
805 * import { useCallback, useState } from "react";
806 * import { BlockerFunction, useBlocker } from "react-router";
807 *
808 * export function ImportantForm() {
809 * const [value, setValue] = useState("");
810 *
811 * const shouldBlock = useCallback<BlockerFunction>(
812 * () => value !== "",
813 * [value]
814 * );
815 * const blocker = useBlocker(shouldBlock);
816 *
817 * return (
818 * <form
819 * onSubmit={(e) => {
820 * e.preventDefault();
821 * setValue("");
822 * if (blocker.state === "blocked") {
823 * blocker.proceed();
824 * }
825 * }}
826 * >
827 * <input
828 * name="data"
829 * value={value}
830 * onChange={(e) => setValue(e.target.value)}
831 * />
832 *
833 * <button type="submit">Save</button>
834 *
835 * {blocker.state === "blocked" ? (
836 * <>
837 * <p style={{ color: "red" }}>
838 * Blocked the last navigation to
839 * </p>
840 * <button
841 * type="button"
842 * onClick={() => blocker.proceed()}
843 * >
844 * Let me through
845 * </button>
846 * <button
847 * type="button"
848 * onClick={() => blocker.reset()}
849 * >
850 * Keep me here
851 * </button>
852 * </>
853 * ) : blocker.state === "proceeding" ? (
854 * <p style={{ color: "orange" }}>
855 * Proceeding through blocked navigation
856 * </p>
857 * ) : (
858 * <p style={{ color: "green" }}>
859 * Blocker is currently unblocked
860 * </p>
861 * )}
862 * </form>
863 * );
864 * }
865 * ```
866 *
867 * @public
868 * @category Hooks
869 * @mode framework
870 * @mode data
871 * @param shouldBlock Either a boolean or a function returning a boolean which
872 * indicates whether the navigation should be blocked. The function format
873 * receives a single object parameter containing the `currentLocation`,
874 * `nextLocation`, and `historyAction` of the potential navigation.
875 * @returns A {@link Blocker} object with state and reset functionality
876 */
877declare function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;
878type UseRouteArgs = [] | [routeId: keyof RouteModules];
879type UseRouteResult<Args extends UseRouteArgs> = Args extends [] ? UseRoute<unknown> : Args extends ["root"] ? UseRoute<"root"> : Args extends [infer RouteId extends keyof RouteModules] ? UseRoute<RouteId> | undefined : never;
880type UseRoute<RouteId extends keyof RouteModules | unknown> = {
881 handle: RouteId extends keyof RouteModules ? RouteModules[RouteId] extends {
882 handle: infer handle;
883 } ? handle : unknown : unknown;
884 loaderData: RouteId extends keyof RouteModules ? GetLoaderData<RouteModules[RouteId]> | undefined : unknown;
885 actionData: RouteId extends keyof RouteModules ? GetActionData<RouteModules[RouteId]> | undefined : unknown;
886};
887declare function useRoute<Args extends UseRouteArgs>(...args: Args): UseRouteResult<Args>;
888/**
889 * A single route match returned from {@link unstable_useRouterState}. Mirrors
890 * {@link UIMatch} minus the data-related fields (`data`, `loaderData`).
891 */
892type unstable_RouterStateMatch<Handle = unknown> = Omit<UIMatch<unknown, Handle>, "data" | "loaderData">;
893/**
894 * The shape of the `active` variant returned from
895 * {@link unstable_useRouterState}.
896 */
897type unstable_RouterStateActiveVariant = {
898 location: Location;
899 searchParams: URLSearchParams;
900 params: Params;
901 matches: unstable_RouterStateMatch[];
902 type: Action;
903};
904/**
905 * The shape of the `pending` variant returned from
906 * {@link unstable_useRouterState}. Extends
907 * {@link unstable_RouterStateActiveVariant} with the navigation `state` and
908 * submission fields mirroring {@link useNavigation} — submission fields are
909 * populated when the in-flight navigation was triggered by a form submission,
910 * otherwise `undefined`.
911 */
912type unstable_RouterStatePendingVariant = unstable_RouterStatePendingVariants[keyof unstable_RouterStatePendingVariants];
913type unstable_RouterStatePendingVariants = {
914 Loading: unstable_RouterStateActiveVariant & Omit<NavigationStates["Loading"], "matches" | "historyAction">;
915 Submitting: unstable_RouterStateActiveVariant & Omit<NavigationStates["Submitting"], "matches" | "historyAction">;
916};
917/**
918 * The return shape of {@link unstable_useRouterState}.
919 *
920 * `active` reflects the currently-committed location. `pending` reflects the
921 * in-flight navigation (if any).
922 */
923type unstable_RouterState = {
924 active: unstable_RouterStateActiveVariant;
925 pending: unstable_RouterStatePendingVariant | null;
926};
927/**
928 * A unified hook for reading router state: current (`active`) and in-flight
929 * (`pending`) locations, search params, params, matches, and navigation type.
930 *
931 * This hook consolidates the information you used to get from {@link useLocation},
932 * {@link useSearchParams}, {@link useParams}, {@link useMatches}, {@link useNavigation},
933 * and {@link useNavigationType} into a single hook.
934 *
935 *
936 * @example
937 * import { unstable_useRouterState as useRouterState } from "react-router";
938 *
939 * let { active, pending } = useRouterState();
940 *
941 * // Active is always populated with the current location
942 * active.location; // replaces `useLocation()`
943 * active.searchParams; // replaces `useSearchParams()[0]`
944 * active.params; // replaces `useParams()`
945 * active.matches; // replaces `useMatches()`
946 * active.type; // replaces `useNavigationType()`
947 *
948 * // Pending is only populated during a navigation
949 * pending.location; // replaces `useNavigation().location`
950 * pending.searchParams; // equivalent to `new URLSearchParams(useNavigation().search)`
951 * pending.params; // Not directly accessible today
952 * pending.matches; // Not directly accessible today
953 * pending.type; // Not directly accessible today
954 * pending.state; // replaces `useNavigation().state`
955 * pending.formMethod; // replaces useNavigation().formMethod
956 * pending.formAction; // replaces useNavigation().formAction
957 * pending.formEncType; // replaces useNavigation().formEncType
958 * pending.formData; // replaces useNavigation().formData
959 * pending.json; // replaces useNavigation().json
960 * pending.text; // replaces useNavigation().text
961 *
962 * @name unstable_useRouterState
963 * @public
964 * @category Hooks
965 * @mode framework
966 * @mode data
967 * @returns The current router state with `active` and `pending` variants
968 */
969declare function useRouterState(): unstable_RouterState;
970//#endregion
971export { NavigateFunction, unstable_RouterState, unstable_RouterStateActiveVariant, unstable_RouterStatePendingVariant, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRoute, useRouteError, useRouteLoaderData, useRouterState, useRoutes };
\No newline at end of file