Created
August 27, 2022 09:22
-
-
Save amirrezasalimi/37129cb7d39796f58bff2f030f236984 to your computer and use it in GitHub Desktop.
nextjs prevent route change hook (typescript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IRouteChangeProps { | |
routeChangeFn: () => boolean | |
} | |
const useRouteChange = (props: IRouteChangeProps) => { | |
const router = useRouter(); | |
const routeChangeStart = () => { | |
const close_res = props.routeChangeFn(); | |
if (!close_res) { | |
router.events.emit('routeChangeError', router.asPath, { shallow: true }); | |
throw 'Abort route change. Please ignore this error.'; | |
} | |
} | |
useEffect(() => { | |
router.events.on('routeChangeStart', routeChangeStart); | |
return () => { | |
router.events.off('routeChangeStart', routeChangeStart); | |
} | |
}, [routeChangeStart]) | |
} | |
export default useRouteChange; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example: