File size: 846 Bytes
339aa1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useMemo } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { buildUrl, safeDecodeURIComponent } from 'next-basics';

export function useNavigation(): {
  pathname: string;
  query: { [key: string]: string };
  router: any;
  renderUrl: (params: any, reset?: boolean) => string;
} {
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();

  const query = useMemo(() => {
    const obj = {};

    for (const [key, value] of params.entries()) {
      obj[key] = safeDecodeURIComponent(value);
    }

    return obj;
  }, [params]);

  function renderUrl(params: any, reset?: boolean) {
    return reset ? pathname : buildUrl(pathname, { ...query, ...params });
  }

  return { pathname, query, router, renderUrl };
}

export default useNavigation;