diff --git a/src/hooks/useHandlePageRefresh.ts b/src/hooks/useHandlePageRefresh.ts new file mode 100644 index 00000000..b8e2f468 --- /dev/null +++ b/src/hooks/useHandlePageRefresh.ts @@ -0,0 +1,30 @@ +import { useEffect } from "react"; +import { abortController } from "@/services/helpers/abortController"; + +/** + * This hook is used to handle page refresh events. + * + * - HTTP requests are prevented from being sent when the user refreshes the page. + * - The `handlePageRefresh` fn, if provided, is called with the {@link BeforeUnloadEvent} + * when the user refreshes the page. + * + * @param handlePageRefresh - A function to call when the user refreshes the page. + */ +export const useHandlePageRefresh = (handlePageRefresh?: PageRefreshHandler) => { + // EFFECT: Prevent the http request from being sent when the user refreshes the page + useEffect(() => { + const handleBeforeUnload = (event: BeforeUnloadEvent) => { + event.preventDefault(); + abortController.abort(); + if (handlePageRefresh) handlePageRefresh(event); + }; + + window.addEventListener("beforeunload", handleBeforeUnload); + + return () => { + window.removeEventListener("beforeunload", handleBeforeUnload); + }; + }, [handlePageRefresh]); +}; + +export type PageRefreshHandler = (event: BeforeUnloadEvent) => void; diff --git a/src/layouts/RootAppLayout/RootAppLayout.tsx b/src/layouts/RootAppLayout/RootAppLayout.tsx index afe5e870..4e66407d 100644 --- a/src/layouts/RootAppLayout/RootAppLayout.tsx +++ b/src/layouts/RootAppLayout/RootAppLayout.tsx @@ -3,6 +3,7 @@ import { styled } from "@mui/material/styles"; import { globalClassNames } from "@/app/GlobalStyles"; import { AppBar, useAppBarHeight } from "@/components/AppBar"; import { useAuthRefresh } from "@/hooks/useAuthRefresh"; +import { useHandlePageRefresh } from "@/hooks/useHandlePageRefresh"; import { rootAppLayoutElementIDs } from "./elementIDs"; /** @@ -15,6 +16,7 @@ import { rootAppLayoutElementIDs } from "./elementIDs"; */ export const RootAppLayout = () => { useAuthRefresh(); + useHandlePageRefresh(); return (