Skip to content

Commit

Permalink
add use Google Analytics hook
Browse files Browse the repository at this point in the history
  • Loading branch information
arviinmo committed Sep 14, 2022
1 parent 6b619f7 commit f5e7b9c
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Hooks/useGoogleAnalytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useEffect } from "react";

export type UseGoogleAnalyticsProps = {
id: string;
startLoading: boolean;
delay: number;
};

export const useGoogleAnalytics = ({
id,
startLoading,
delay = 0
}: UseGoogleAnalyticsProps) => {
useEffect(() => {
if (startLoading) {
if (!id) {
throw new Error("Must provide id");
}
setTimeout(() => {
let script = document.createElement("script");
script.type = "text/javascript";
script.src = `https://www.googletagmanager.com/gtag/js?id=${id}`;
document.body.appendChild(script);
//@ts-ignore
window.dataLayer = window.dataLayer || [];

function gtag() {
//@ts-ignore
window.dataLayer.push(arguments);
}

//@ts-ignore
gtag("js", new Date());
//@ts-ignore
gtag("config", id, {
anonymize_ip: true,
cookie_expires: 0
});
}, delay);
}
}, [delay, id, startLoading]);
};

0 comments on commit f5e7b9c

Please sign in to comment.