Skip to content

Commit

Permalink
feat: add useHandlePageRefresh to stop refreshes
Browse files Browse the repository at this point in the history
  • Loading branch information
trevor-anderson committed Feb 22, 2024
1 parent 4264c83 commit ce92f02
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/hooks/useHandlePageRefresh.ts
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 2 additions & 0 deletions src/layouts/RootAppLayout/RootAppLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand All @@ -15,6 +16,7 @@ import { rootAppLayoutElementIDs } from "./elementIDs";
*/
export const RootAppLayout = () => {
useAuthRefresh();
useHandlePageRefresh();

return (
<StyledDiv id={rootAppLayoutElementIDs.root} className={globalClassNames.scrollbarForceHidden}>
Expand Down

0 comments on commit ce92f02

Please sign in to comment.