Last active
October 17, 2022 04:06
-
-
Save cjkihl/155f88abe4c6befccbc017ec228c2314 to your computer and use it in GitHub Desktop.
NextJS GTM useEvents.ts
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
import { useRouter } from "next/router"; | |
import { useEffect } from "react"; | |
const useEvents = () => { | |
const router = useRouter(); | |
useEffect(() => { | |
const onRouteChangeComplete = (url: string) => { | |
window.dataLayer?.push({ | |
event: "route_complete", | |
url, | |
}); | |
}; | |
const onRouteChangeError = (error: { cancelled: boolean }, url: string) => { | |
// Don't fire on cancelled routes | |
if (error.cancelled) return; | |
window.dataLayer?.push({ | |
event: "route_error", | |
url, | |
error: JSON.stringify(error), | |
}); | |
}; | |
router.events.on("routeChangeComplete", onRouteChangeComplete); | |
router.events.on("routeChangeError", onRouteChangeError); | |
return () => { | |
router.events.off("routeChangeComplete", onRouteChangeComplete); | |
router.events.off("routeChangeError", onRouteChangeError); | |
}; | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []); | |
return null; | |
}; | |
export default useEvents; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment