Estoy tratando de interceptar el cambio de ruta según el valor boolean
(si hay cambios no guardados).
Encontré las discusiones relacionadas con el tema e intenté implementarlas, pero no funciona correctamente. Al hacer clic en el botón Cancel
, aparece este error
TypeError: Cannot read properties of undefined (reading 'shallow') const routeChangeStart = (url: string) => { 55 | if (Router.asPath !== url && unsavedChanges && !confirm(message)) { > 56 | Router.events.emit('routeChangeError') | ^ 57 | Router.replace(Router, Router.asPath) 58 | throw 'Abort route change. Please ignore this error.' 59 | }
Además, al hacer clic en el botón cancel
, cambiará la URL 1 paso atrás. Digamos que mi url es localhost:3000/products/10
, se convertirá en localhost:3000/products
y generará el error descrito anteriormente. No estoy seguro de si es el mejor enfoque, o si solo es posible con next.js router
, es decir, sin global window properties
, por lo que se agradecerá cualquier ayuda.
Fragmento de código relacionado con el tema a continuación.
import Router from 'next/router' ..... //// const [unsavedChanges, setUnsavedChanges] = useState<boolean>(true) const message = 'Do you want to leave?' useEffect(() => { const routeChangeStart = (url: string) => { if (Router.asPath !== url && unsavedChanges && !confirm(message)) { Router.events.emit('routeChangeError') Router.replace(Router, Router.asPath) throw 'Abort route change. Please ignore this error.' } } const beforeunload = (e: any) => { if (unsavedChanges) { e.preventDefault() e.returnValue = message return message } } window.addEventListener('beforeunload', beforeunload) Router.events.on('routeChangeStart', routeChangeStart) return () => { window.removeEventListener('beforeunload', beforeunload) Router.events.off('routeChangeStart', routeChangeStart) } }, [unsavedChanges])