Skip to content

Commit

Permalink
Allow monkey-patching navigate function
Browse files Browse the repository at this point in the history
  • Loading branch information
Frazi1 committed Jan 29, 2022
1 parent 5dc07e2 commit 713c702
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
6 changes: 4 additions & 2 deletions packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ import {
useParams,
useResolvedPath,
useRoutes,
useOutletContext
useOutletContext,
patchNavigate
} from "react-router";
import type { To } from "react-router";

Expand Down Expand Up @@ -73,7 +74,8 @@ export {
useParams,
useResolvedPath,
useRoutes,
useOutletContext
useOutletContext,
patchNavigate
};

export type {
Expand Down
6 changes: 4 additions & 2 deletions packages/react-router-native/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ import {
useParams,
useResolvedPath,
useRoutes,
useOutletContext
useOutletContext,
patchNavigate
} from "react-router";
import type { To } from "react-router";

Expand Down Expand Up @@ -65,7 +66,8 @@ export {
useParams,
useResolvedPath,
useRoutes,
useOutletContext
useOutletContext,
patchNavigate
};

export type {
Expand Down
14 changes: 14 additions & 0 deletions packages/react-router/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -497,13 +497,27 @@ export interface NavigateOptions {
state?: any;
}

let decoratedNavigate: (() => NavigateFunction) | null = null

export function patchNavigate(decorator: (original: () => NavigateFunction) => () => NavigateFunction): void {
decoratedNavigate = decorator(useNavigateInternal)
}
/**
* Returns an imperative method for changing the location. Used by <Link>s, but
* may also be used by other elements to change the location.
*
* @see https://reactrouter.com/docs/en/v6/api#usenavigate
*/
export function useNavigate(): NavigateFunction {
if (decoratedNavigate) {
return decoratedNavigate()
}

// eslint-disable-next-line react-hooks/rules-of-hooks
return useNavigateInternal()
}

function useNavigateInternal(): NavigateFunction {
invariant(
useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
Expand Down

0 comments on commit 713c702

Please sign in to comment.