Skip to content

Instantly share code, notes, and snippets.

@arekbartnik
Forked from Jayphen/whatev.js
Created August 25, 2020 21:07
Show Gist options
  • Select an option

  • Save arekbartnik/3a21a1fe8affc26f66bbf89ec5211554 to your computer and use it in GitHub Desktop.

Select an option

Save arekbartnik/3a21a1fe8affc26f66bbf89ec5211554 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)");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment