Skip to content

Instantly share code, notes, and snippets.

@Aakash1103Jha
Last active April 17, 2022 19:27
Show Gist options
  • Save Aakash1103Jha/17c45b3fc599485c59e5529acbb27fea to your computer and use it in GitHub Desktop.
Save Aakash1103Jha/17c45b3fc599485c59e5529acbb27fea to your computer and use it in GitHub Desktop.
A function to keep a track of the pages visited by users and to send data to Firebase Analytics.
import { useLocation } from "react-router";
const App = () => {
const { pathname, search } = useLocation();
const analytics = useCallback(() => {
trackPathForAnalytics({ path: pathname, search: search, title: pathname.split("/")[1] });
}, [pathname, search]);
useEffect(() => {
analytics();
}, [analytics]);
// more code...
}
export default App.
import { GA4React } from "ga-4-react";
const ga4react = new GA4React("G-0SPQ2Z9EE2").initialize();
export interface AnalyticsData {
path: string;
search: string;
title: string;
}
const trackPathForAnalytics = (data: AnalyticsData) => {
const { path, search, title } = data;
ga4react
.then((ga) => {
ga.pageview(path, search, title);
})
.catch((err) => console.error(`Analytics failed: ${err}`));
};
export default trackPathForAnalytics;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment