Tracking SPAs
For SPAs you can install Dreamdata Analytics directly through our NPM package:
# npm
npm install @dreamdata/analytics-next
# yarn
yarn add @dreamdata/analytics-next
# pnpm
pnpm add @dreamdata/analytics-next
After installing the package you initialize it as done below:
import { AnalyticsBrowser } from '@dreamdata/analytics-next'
export const dreamdata = AnalyticsBrowser.load({ writeKey: '<YOUR_WRITE_KEY>' })
You get the write key YOUR_WRITE_KEY
by navigating to the
app.dreamdata.io/<SLUG>/sources/dreamdata
page in the app.
Page Tracking
In SPAs, navigating between views does not involve loading new HTML pages. Instead, views are rendered dynamically based on route changes, typically handled by routing libraries.
React Example
If you're using React Router, you can make use of the useLocation
and
useEffect
hooks to get the equivalent of page tracking as done below. Note
that this needs to be in a top-level component.
import { useLocation } from 'react-router-dom'
import { useEffect } from 'react'
const App = () => {
const location = useLocation()
useEffect(() => {
dreamdata.page()
}, [location.pathname])
// Rest of app...
}
This snippet ensures that dreamdata.page()
is called every time the URL's
pathname changes, capturing each navigation event.
Next Example
See
this example
from Vercel. You can substitute the dependency @segment/analytics-next
for
@dreamdata/analytics-next
.
Angular Example
In Angular, route changes are tracked similarly by subscribing to router events:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
// Component metadata...
})
export class AppComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
dreamdata.page();
}
});
}
}
Tracking Forms
Tracking forms in SPAs often involves attaching handlers to form submission events.
Take a look at Manual Tracking for more information.