Last active
April 17, 2022 19:27
-
-
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.
This file contains 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 { 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. |
This file contains 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 { 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