Skip to content

Instantly share code, notes, and snippets.

@Jayphen
Last active July 6, 2021 19:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Jayphen/dc2db7591cd0735cefa586b2f5facacf to your computer and use it in GitHub Desktop.
Save Jayphen/dc2db7591cd0735cefa586b2f5facacf to your computer and use it in GitHub Desktop.
Page tracking in Sapper
// 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)");
}
});
@mehdiraized
Copy link

how is work on svelte kit ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment