Created
October 10, 2021 01:21
-
-
Save DavidWells/37ee749fd467909ad88273e11a0d96d3 to your computer and use it in GitHub Desktop.
Example of persisting page views via analytics package
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 Analytics from 'analytics' | |
import onRouteChange from '@analytics/router-utils' | |
const persistPageViewsPlugin = { | |
name: 'persist-page-data-plugin', | |
page: ({ payload }) => { | |
const { properties } = payload | |
const pageView = { | |
path: properties.path, | |
title: properties.title, | |
url: properties.url | |
} | |
setViews(getViews().concat(pageView.path)) | |
}, | |
} | |
const pagesViewedKey = 'PAGES_VIEWED' | |
// Use getViews elsewhere in app | |
function getViews() { | |
return JSON.parse((localStorage.setItem(pagesViewedKey) || '[]')) | |
} | |
function setViews(data) { | |
return localStorage.setItem(pagesViewedKey, JSON.stringify(data)) | |
} | |
const analytics = Analytics({ | |
app: 'app-name', | |
plugins: [ | |
persistPageViewsPlugin | |
] | |
}) | |
/* Track initial page view */ | |
analytics.page() | |
/* (optional for SPA) Track page views on SPA route changes */ | |
onRouteChange((newPath) => { | |
// trigger page view | |
analytics.page() | |
}) | |
export default analytics |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment