From 713c702af13955132710203b743540d2ff16b33a Mon Sep 17 00:00:00 2001 From: dmitry-vychikov Date: Sat, 29 Jan 2022 14:43:45 +0300 Subject: [PATCH] Allow monkey-patching navigate function --- packages/react-router-dom/index.tsx | 6 ++++-- packages/react-router-native/index.tsx | 6 ++++-- packages/react-router/index.tsx | 14 ++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/react-router-dom/index.tsx b/packages/react-router-dom/index.tsx index 40cbe72d2f..640e98f515 100644 --- a/packages/react-router-dom/index.tsx +++ b/packages/react-router-dom/index.tsx @@ -24,7 +24,8 @@ import { useParams, useResolvedPath, useRoutes, - useOutletContext + useOutletContext, + patchNavigate } from "react-router"; import type { To } from "react-router"; @@ -73,7 +74,8 @@ export { useParams, useResolvedPath, useRoutes, - useOutletContext + useOutletContext, + patchNavigate }; export type { diff --git a/packages/react-router-native/index.tsx b/packages/react-router-native/index.tsx index 1660ba1e3d..fd3cce1c0b 100644 --- a/packages/react-router-native/index.tsx +++ b/packages/react-router-native/index.tsx @@ -31,7 +31,8 @@ import { useParams, useResolvedPath, useRoutes, - useOutletContext + useOutletContext, + patchNavigate } from "react-router"; import type { To } from "react-router"; @@ -65,7 +66,8 @@ export { useParams, useResolvedPath, useRoutes, - useOutletContext + useOutletContext, + patchNavigate }; export type { diff --git a/packages/react-router/index.tsx b/packages/react-router/index.tsx index 135d2e6bae..7e339306cd 100644 --- a/packages/react-router/index.tsx +++ b/packages/react-router/index.tsx @@ -497,6 +497,11 @@ 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 s, but * may also be used by other elements to change the location. @@ -504,6 +509,15 @@ export interface NavigateOptions { * @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