-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add useHandlePageRefresh to stop refreshes
- Loading branch information
1 parent
4264c83
commit ce92f02
Showing
2 changed files
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters