All files / src/hooks/common/router useRedirect.tsx

70% Statements 21/30
50% Branches 7/14
75% Functions 6/8
76.92% Lines 20/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                      73x 6235x   6235x 12x 12x 12x 11x   12x           6235x 5x   6235x                       73x       20x 20x   20x 16x   16x                   16x   16x 16x        
import NiceModal from "@ebay/nice-modal-react";
import { EffectCallback, useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
 
type TPageRedirectOptions = {
  subpath?: string;
  sectionElId?: string;
  scrollIntoView?: boolean;
  routeParams?: { tab: string };
};
 
const useRedirect = () => {
  const navigate = useNavigate();
 
  const redirectToPage = (path: string, options?: TPageRedirectOptions) => {
    const url = options?.subpath ? `${path}/?path=${options.subpath}` : path;
    const params = options?.routeParams;
    if (params) navigate(url, { state: { params } });
    else navigate(url);
 
    Iif (options?.sectionElId) {
      const section = document.getElementById(options?.sectionElId);
      if (options?.scrollIntoView) section?.scrollIntoView();
    }
  };
 
  const redirectToModal = (modalName: string, modalProps?: any) =>
    NiceModal.show(modalName, modalProps);
 
  return {
    redirectToPage,
    redirectToModal,
  };
};
 
export default useRedirect;
 
type TEffectOptions = {
  delay?: number;
};
 
export const useTriggerPathEffect = (
  effect: EffectCallback,
  options?: TEffectOptions,
) => {
  const [params] = useSearchParams();
  const path = params.get("path");
 
  useEffect(() => {
    let timeout: NodeJS.Timeout | null = null;
 
    const triggerEffect = () => {
      if (options?.delay) {
        timeout = setTimeout(() => {
          effect();
        }, options.delay);
      } else {
        effect();
      }
    };
 
    Iif (path) triggerEffect();
 
    return () => {
      Iif (timeout) clearTimeout(timeout);
    };
  }, [path]);
};