This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
website/src/libs/hooks/usePrompt.ts

24 lines
564 B
TypeScript

import { useEffect, useRef, useCallback } from 'react';
export const usePrompt = (when: boolean) => {
const whenRef = useRef(when);
const handleUnload = useCallback((event: BeforeUnloadEvent) => {
if (whenRef.current) {
event.preventDefault();
event.returnValue = '';
}
}, []);
useEffect(() => {
whenRef.current = when;
}, [when]);
useEffect(() => {
window.addEventListener('beforeunload', handleUnload);
return () => {
window.removeEventListener('beforeunload', handleUnload);
};
}, [handleUnload]);
};