'Next/Router emit events
I'm writing a custom hook to prevent a user from navigating away if there's unsaved information (in a form) on a page.
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 error TypeError: Cannot read properties of undefined (reading 'shallow')
import { useRouter } from 'next/router'
import { useEffect, useCallback } from 'react'
export default function usePreventWindowUnload(preventDefault: boolean) {
const confirmMessage = 'Are you sure?'
const router = useRouter()
const onRouterChangeStart = useCallback(() => {
if (preventDefault) {
if (window.confirm(confirmMessage)) {
return true
}
}
// line causing error
router.events.emit('routeChangeError')
throw 'cancelled route change'
,} [preventDefault])
useEffect(() => {
router.events.on('routeChangeStart', onRouteChangeStart)
return () => {
router.events.off('routeChangeStart', onRouteChangeStart)
}
}, [preventDefault])
}
How do I fix this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
