Reputation: 15627
Within Next.js, how would I validate a route before its loaded?
As per the API docs, routeChangeStart
is triggered before route change, however, I am unable to cancel the event once triggered.
useEffect(() => {
events.on("routeChangeStart", routerChangeHandler);
return (() => events.off("routeChangeStart", routerChangeHandler));
});
const routerChangeHandler = (url) => {
if(/* check something */){
// stop the new page load and stay on the page
return false;
}
};
Upvotes: 1
Views: 688
Reputation: 13078
You can try throwing an error to cancel the navigation:
events.on('routeChangeStart', () => {
throw new Error('AbortError');
});
Also you can try to dispatch routeChangeError
:
events.emit('routeChangeError');
Upvotes: 2
Reputation: 512
I think you should do something like this: Next JS: Warn User for Unsaved Form before Route Change
Upvotes: 2