How to warn user on page leave of any kind in next js app router
Unanswered
Cape lion posted this in #help-forum
Cape lionOP
This is how i did it in next page router
const warningText =
'You have an ongoing file upload. If you leave this page, the upload will be canceled. Are you sure you want to leave?';
useEffect(() => {
const handleWindowClose = (e) => {
if (!loading) return;
e.preventDefault();
return (e.returnValue = warningText);
};
const handleBrowseAway = () => {
if (!loading) return;
if (window.confirm(warningText)) return;
router.events.emit('routeChangeError');
throw 'routeChange aborted.';
};
window.addEventListener('beforeunload', handleWindowClose);
router.events.on('routeChangeStart', handleBrowseAway);
return () => {
window.removeEventListener('beforeunload', handleWindowClose);
router.events.off('routeChangeStart', handleBrowseAway);
};
}, [loading]);6 Replies
European sprat
There's no router events with app router
Cape lionOP
yeah right, so how do i manage this w/ app router
any code samples to replicate this
European sprat
There's no way to intercept the navigation away and prevent it. You can check things like the various JavaScript events such as beforeunload, but it's not foolproof and won't catch every nav away. Popstate changes like back and forward don't fire those JS events at all
The tldr I found was to use some kind of auto save but I don't know how that works for uploading
Cape lionOP
oh damn that's a big negative of next app router then