aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-redirection/use-redirection.ts
blob: 1592a33519142a276ab2617b71e7041e2d49bf37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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]);
};