add confirm when leave from add or edit question page

This commit is contained in:
Majd_dk 2025-09-28 11:48:11 +03:00
parent 761be504cf
commit 34b0ad8d4a

View File

@ -3,7 +3,6 @@ import { useTranslation } from "react-i18next";
const useUnsavedChangesWarning = (unsavedChanges: boolean) => {
const [t] = useTranslation();
useEffect(() => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (unsavedChanges) {
@ -14,29 +13,37 @@ const useUnsavedChangesWarning = (unsavedChanges: boolean) => {
}
};
const handleNavigation = (event: MouseEvent) => {
if (unsavedChanges) {
console.log(t("Access denied: You have unsaved changes!"));
event.preventDefault();
}
};
const handleNavigation = (event: Event) => {
// const target = event.target as HTMLElement;
if (unsavedChanges ) {
const leave = window.confirm(t("validation.You have unsaved changes! Are you sure you want to leave?"));
if (leave) return ;
event.stopPropagation();
event.preventDefault();
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
// Intercept link clicks (example for <a> elements)
document.querySelectorAll("a").forEach((link) => {
// document.addEventListener("click", handleNavigation);
document.querySelectorAll(".link").forEach((link) => {
link.addEventListener("click", handleNavigation);
});
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
document.querySelectorAll(".link").forEach((link) => {
link.removeEventListener("click", handleNavigation);
});
// Clean up event listeners
document.querySelectorAll("a").forEach((link) => {
link.removeEventListener("click", handleNavigation);
});
document.removeEventListener("click", handleNavigation);
};
}, [unsavedChanges, t]);
}, [unsavedChanges]);
};
export default useUnsavedChangesWarning;