aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-redirection/use-redirection.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/hooks/use-redirection/use-redirection.ts')
-rw-r--r--src/utils/hooks/use-redirection/use-redirection.ts41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/utils/hooks/use-redirection/use-redirection.ts b/src/utils/hooks/use-redirection/use-redirection.ts
new file mode 100644
index 0000000..1592a33
--- /dev/null
+++ b/src/utils/hooks/use-redirection/use-redirection.ts
@@ -0,0 +1,41 @@
+import { useRouter } from 'next/router';
+import { useEffect } from 'react';
+
+export type UseRedirectionConfig = {
+ /**
+ * Should the url be replaced in the history?
+ *
+ * @default false
+ */
+ isReplacing?: boolean;
+ /**
+ * The destination.
+ */
+ to: string;
+ /**
+ * Redirect only when the current path matches the condition.
+ *
+ * @param {string} path - The current slug.
+ * @returns {boolean} True if the path matches.
+ */
+ whenPathMatches?: (path: string) => boolean;
+};
+
+export const useRedirection = ({
+ isReplacing = false,
+ to,
+ whenPathMatches,
+}: UseRedirectionConfig) => {
+ const router = useRouter();
+
+ useEffect(() => {
+ const shouldRedirect = whenPathMatches
+ ? whenPathMatches(router.asPath)
+ : true;
+
+ if (shouldRedirect) {
+ if (isReplacing) router.replace(to, undefined, { shallow: true });
+ else router.push(to);
+ }
+ }, [isReplacing, router, to, whenPathMatches]);
+};