-
-
Save arekbartnik/3a21a1fe8affc26f66bbf89ec5211554 to your computer and use it in GitHub Desktop.
Page tracking in Sapper
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
| // stores/location.ts | |
| import { writable, derived } from "svelte/store"; | |
| import { beforeUpdate } from "svelte"; | |
| export interface LocationStore { | |
| current: Location | undefined; | |
| previous: Location | undefined; | |
| } | |
| export const location = writable<LocationStore>({ | |
| current: undefined, | |
| previous: undefined, | |
| }); | |
| export const routeHasChanged = derived(location, ($l) => { | |
| if (!$l.previous || !$l.current) return true; | |
| if ($l.previous.pathname !== $l.current.pathname) return true; | |
| return false; | |
| }); | |
| export function trackLocation(): void { | |
| beforeUpdate(() => { | |
| if (typeof window !== "undefined") { | |
| location.update((l) => { | |
| return { | |
| previous: l.current, | |
| current: { ...window.location }, | |
| }; | |
| }); | |
| } | |
| }); | |
| } | |
| // in _layout.svelte | |
| import { trackLocation } from "../stores/location"; | |
| trackLocation(); | |
| // wherever I wanna do something on route change (in my case, sending tracking events to an analytics endpoint | |
| afterUpdate(() => { | |
| if ($routeHasChanged) { | |
| console.log("route changed, do the thing"); | |
| } else { | |
| console.log("route did not in fact change (or maybe only the search or hash changed)"); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment