save, create and view reports in dashboard
This commit is contained in:
35
apps/web/src/hooks/useQueryParams.ts
Normal file
35
apps/web/src/hooks/useQueryParams.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useRouter } from "next/router";
|
||||
import { type z } from "zod";
|
||||
|
||||
export function useQueryParams<Z extends z.ZodTypeAny = z.ZodNever>(zod: Z) {
|
||||
const router = useRouter();
|
||||
const value = zod.safeParse(router.query);
|
||||
|
||||
return useMemo(() => {
|
||||
function setQueryParams(newValue: Partial<z.infer<Z>>) {
|
||||
return router
|
||||
.replace({
|
||||
pathname: router.pathname,
|
||||
query: {
|
||||
...router.query,
|
||||
...newValue,
|
||||
},
|
||||
})
|
||||
.catch(() => {
|
||||
// ignore
|
||||
});
|
||||
}
|
||||
|
||||
if (value.success) {
|
||||
return { ...value.data, setQueryParams } as z.infer<Z> & {
|
||||
setQueryParams: typeof setQueryParams;
|
||||
};
|
||||
}
|
||||
return { ...router.query, setQueryParams } as z.infer<Z> & {
|
||||
setQueryParams: typeof setQueryParams;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [router.asPath, value.success]);
|
||||
}
|
||||
21
apps/web/src/hooks/useRouterBeforeLeave.ts
Normal file
21
apps/web/src/hooks/useRouterBeforeLeave.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export function useRouterBeforeLeave(callback: () => void) {
|
||||
const router = useRouter();
|
||||
const prevUrl = useRef(router.asPath);
|
||||
|
||||
useEffect(() => {
|
||||
const handleRouteChange = (url: string) => {
|
||||
if (prevUrl.current !== url) {
|
||||
callback()
|
||||
}
|
||||
prevUrl.current = url;
|
||||
};
|
||||
|
||||
router.events.on("routeChangeStart", handleRouteChange);
|
||||
return () => {
|
||||
router.events.off("routeChangeStart", handleRouteChange);
|
||||
};
|
||||
}, [router, callback]);
|
||||
}
|
||||
Reference in New Issue
Block a user