UNPKG

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