router.events.emit('routeChangeError'); is not working
See original GitHub issue"next": "12.0.10",
"nextjs-progressbar": "^0.0.13",
// app.tsx
...
<NextNProgress stopDelayMs={0} options={{ showSpinner: false }} />
// form guard
import { useRouter } from 'next/router';
import { useEffect } from 'react';
export const useFormGuard = (isDirty: boolean) => {
const router = useRouter();
const message = 'ok?';
const pageChangeHandler = () => {
const answer = window.confirm(message);
if (!answer) {
// crash here
router.events.emit('routeChangeError');
// throw 'routeChange aborted.';
}
};
const beforeUnloadhandler = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = message;
};
useEffect(() => {
if (isDirty) {
router.events.on('routeChangeStart', pageChangeHandler);
window.addEventListener('beforeunload', beforeUnloadhandler);
return () => {
router.events.off('routeChangeStart', pageChangeHandler);
window.removeEventListener('beforeunload', beforeUnloadhandler);
};
}
}, [isDirty, router]);
};
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (1 by maintainers)
Top Results From Across the Web
Next/Router emit events · Discussion #34071 - GitHub
To do this, I want to emit a router event when a route change has been cancelled. However, router.events.emit('routeChangeStart') causes a a type...
Read more >Next/Router emit events - Stack Overflow
To do this, I want to emit a router event when a route change has been cancelled. However, router.events.emit('routeChangeStart') causes a a ...
Read more >Understanding Next.js routeChangeStart and router events
In this article, we are going to take a look at the routeChangeStart event as well as the other router events in Next.js....
Read more >next/router | Next.js
Router events should be registered when a component mounts (useEffect or componentDidMount / componentWillUnmount) or imperatively when an event happens. If a ...
Read more >Layout issue when pushing a route in Next.js
the header shows fine, but when the router pushes to the next route, ... routeChangeComplete) router.events.on('routeChangeError', ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@imranbarbhuiya solved. Thank you for your kind answer!
this can help maybe