Skip to content

Commit

Permalink
Add gtag functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Stephen Chiang committed Apr 29, 2022
1 parent f632678 commit 5420144
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,54 @@ export const meta: MetaFunction = () => ({

type LoaderData = {
user: Awaited<ReturnType<typeof getUser>>;
gaTrackingId: string | undefined;
};

export const loader: LoaderFunction = async ({ request }) => {
return json<LoaderData>({
user: await getUser(request),
gaTrackingId: process.env.GA_TRACKING_ID,
});
};

const GA = ({ trackingId }: { trackingId: string }): JSX.Element => (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${trackingId}`}
/>
<script
async
id="gtag-init"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${trackingId}');
`,
}}
/>
</>
);

export default function App() {
const { gaTrackingId, user } = useLoaderData<LoaderData>();
const location = useLocation();

// GA pageview
useEffect(() => {
if (gaTrackingId?.length) {
gtag.pageview(location.pathname, gaTrackingId);
}
}, [location, gaTrackingId]);

// GA main script load
const gtagScript =
process.env.NODE_ENV === "development" || !gaTrackingId ? null : (
<GA trackingId={gaTrackingId} />
);

return (
<html lang="en" className="h-full">
<head>
Expand Down

0 comments on commit 5420144

Please sign in to comment.