I want to warn the user when some changes are made by the user and he tries to leave the page. This is my react code it's working fine on page reload and or when try to close the tab. but when I try to goto another page this doesn't work.
useEffect(() => {
const handleBeforeUnload = (e: any) => {
console.log('123');
if (hasUnsavedChanges) {
e.preventDefault();
e.returnValue = '';
return e.returnValue;
}
};
// Attach the event listener
window.addEventListener('beforeunload', handleBeforeUnload);
// Clean up the event listener when the component unmounts
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [hasUnsavedChanges]);