aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-redirection.tsx
blob: 5a677e26e57df813b5475bbb3471e355633afca4 (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
import { useRouter } from 'next/router';
import { useEffect } from 'react';

export type RouterQuery = {
  param: string;
  value: string;
};

export type UseRedirectionProps = {
  /**
   * The router query.
   */
  query: RouterQuery;
  /**
   * The redirection url.
   */
  redirectTo: string;
};

/**
 * Redirect to another url when router query match the given parameters.
 *
 * @param {UseRedirectionProps} props - The redirection parameters.
 */
export const useRedirection = ({ query, redirectTo }: UseRedirectionProps) => {
  const router = useRouter();

  useEffect(() => {
    if (router.query[query.param] === query.value) router.push(redirectTo);
  }, [query, redirectTo, router]);
};