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