Skip to content

Commit

Permalink
Externalize analytics into custom hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Sebastian Herrmann committed Aug 21, 2023
1 parent 671e1b4 commit c74292b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
17 changes: 17 additions & 0 deletions src/hooks/useAnalytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { init } from "@socialgouv/matomo-next";
import { useEffect, useRef } from "react";

const MATOMO_URL = process.env.NEXT_PUBLIC_MATOMO_URL as string;
const MATOMO_SITE_ID = process.env.NEXT_PUBLIC_MATOMO_SITE_ID as string;

export function useAnalytics() {
const matomoInitialized = useRef(false);
useEffect(() => {
if (MATOMO_URL && MATOMO_SITE_ID && matomoInitialized.current === false) {
init({ url: MATOMO_URL, siteId: MATOMO_SITE_ID });
}
return () => {
matomoInitialized.current = true;
};
}, []);
}
16 changes: 2 additions & 14 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,15 @@
import { init } from "@socialgouv/matomo-next";
import { NextIntlClientProvider } from "next-intl";
import type { AppProps } from "next/app";
import { useEffect, useRef } from "react";
import "react-tooltip/dist/react-tooltip.css";
import GlobalStyles from "../components/GlobalStyles";

const MATOMO_URL = process.env.NEXT_PUBLIC_MATOMO_URL as string;
const MATOMO_SITE_ID = process.env.NEXT_PUBLIC_MATOMO_SITE_ID as string;
import { useAnalytics } from "../hooks/useAnalytics";

type CustomPageProps = {
messages: IntlMessages;
};

export default function App({ Component, pageProps }: AppProps<CustomPageProps>) {
const matomoInitialized = useRef(false);
useEffect(() => {
if (MATOMO_URL && MATOMO_SITE_ID && matomoInitialized.current === false) {
init({ url: MATOMO_URL, siteId: MATOMO_SITE_ID });
}
return () => {
matomoInitialized.current = true;
};
}, []);
useAnalytics();
return (
<NextIntlClientProvider messages={pageProps.messages}>
<GlobalStyles />
Expand Down

0 comments on commit c74292b

Please sign in to comment.