Confirmar cambios al refrescar el navegador

This commit is contained in:
David Arranz 2026-06-03 15:50:57 +02:00
parent 66623cbe78
commit 834d90f60c

View File

@ -49,12 +49,12 @@ export const UnsavedChangesProvider = ({ isDirty, children }: UnsavedChangesProv
});
}, [isDirty]);
const handleConfirm = useCallback((discardChanges: boolean) => {
if (discardChanges) {
const handleConfirm = useCallback((confirmed: boolean) => {
if (confirmed) {
allowNavigationRef.current = true;
}
resolverRef.current?.(discardChanges);
resolverRef.current?.(confirmed);
resolverRef.current = null;
setOpen(false);
}, []);
@ -94,6 +94,25 @@ export const UnsavedChangesProvider = ({ isDirty, children }: UnsavedChangesProv
};
}, []);
useEffect(() => {
if (!isDirty) return;
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (allowNavigationRef.current) return;
event.preventDefault();
// Necesario para compatibilidad con navegadores legacy.
event.returnValue = "";
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
}, [isDirty]);
const contextValue = useMemo<UnsavedChangesContextValue>(
() => ({
requestConfirm,