Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created October 10, 2021 01:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidWells/37ee749fd467909ad88273e11a0d96d3 to your computer and use it in GitHub Desktop.
Save DavidWells/37ee749fd467909ad88273e11a0d96d3 to your computer and use it in GitHub Desktop.
Example of persisting page views via analytics package
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