From c3e1c1caccbe21e7602bf4e1e3472f0b0d4260bd Mon Sep 17 00:00:00 2001 From: Glenn Verschooren Date: Mon, 22 Jun 2020 14:27:20 +0200 Subject: [PATCH] feat: Make hasPathChanged a configuarable function --- package/src/Guard.tsx | 19 ++++++++++++++----- package/src/GuardedRoute.tsx | 8 +++++++- package/src/types.ts | 5 +++++ 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/package/src/Guard.tsx b/package/src/Guard.tsx index e27d94c..90fd74e 100644 --- a/package/src/Guard.tsx +++ b/package/src/Guard.tsx @@ -24,13 +24,22 @@ interface GuardsResolve { redirect: RouteRedirect; } -const Guard: React.FunctionComponent = ({ children, component, meta, render }) => { +const Guard: React.FunctionComponent = ({ + children, + component, + meta, + render, + pathChanged, + name, +}) => { const routeProps = useContext(RouterContext); const routePrevProps = usePrevious(routeProps); - const hasPathChanged = useMemo( - () => routeProps.location.pathname !== routePrevProps.location.pathname, - [routePrevProps, routeProps], - ); + const hasPathChanged = useMemo(() => { + if (pathChanged && typeof pathChanged === 'function') { + return pathChanged(routePrevProps, routeProps, name); + } + return routeProps.location.pathname !== routePrevProps.location.pathname; + }, [routePrevProps, routeProps]); const fromRouteProps = useContext(FromRouteContext); const guards = useContext(GuardContext); diff --git a/package/src/GuardedRoute.tsx b/package/src/GuardedRoute.tsx index 2d6fcdf..e521148 100644 --- a/package/src/GuardedRoute.tsx +++ b/package/src/GuardedRoute.tsx @@ -15,6 +15,7 @@ const GuardedRoute: React.FunctionComponent = ({ ignoreGlobal, loading, meta, + pathChanged, render, path, ...routeProps @@ -32,7 +33,12 @@ const GuardedRoute: React.FunctionComponent = ({ context={LoadingPageContext} value={loading}> context={ErrorPageContext} value={error}> - + {children} diff --git a/package/src/types.ts b/package/src/types.ts index 197f2e4..ed757df 100644 --- a/package/src/types.ts +++ b/package/src/types.ts @@ -74,6 +74,11 @@ export interface BaseGuardProps { export type PropsWithMeta = T & { meta?: Meta; + pathChanged?: ( + routePrevProps: RouteComponentProps, + routeProps: RouteComponentProps, + path?: string | string[], + ) => boolean; }; export type GuardProviderProps = BaseGuardProps;