From e82295452561a4b577b17206d08c86c7ea7cc83a Mon Sep 17 00:00:00 2001 From: mehdilouraoui Date: Tue, 19 Sep 2023 14:41:58 +0200 Subject: [PATCH] feat: fix posthog --- hooks/usePostHog.tsx | 33 +++++++++++++++++++++++++++++++++ pages/_app.tsx | 28 ++-------------------------- 2 files changed, 35 insertions(+), 26 deletions(-) create mode 100644 hooks/usePostHog.tsx diff --git a/hooks/usePostHog.tsx b/hooks/usePostHog.tsx new file mode 100644 index 0000000..63e0db9 --- /dev/null +++ b/hooks/usePostHog.tsx @@ -0,0 +1,33 @@ +import { useRouter } from 'next/router'; +import posthog from 'posthog-js'; +import { useEffect } from 'react'; + +if (typeof window !== 'undefined') { + posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY ?? '', { + api_host: + process.env.NEXT_PUBLIC_POSTHOG_HOST || + 'https://docs.posthog.archifiltre.fr', + capture_pageview: false, + }); +} + +export const usePostHog = () => { + const router = useRouter(); + + useEffect(() => { + const handleRouteChange = () => { + posthog?.capture('$pageview'); + console.log('capture'); + }; + router.events.on('routeChangeComplete', handleRouteChange); + + return () => { + router.events.off('routeChangeComplete', handleRouteChange); + }; + }, []); +}; + +export const PostHogTracker = () => { + usePostHog(); + return <>; +}; diff --git a/pages/_app.tsx b/pages/_app.tsx index e6a15f1..7782591 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -2,45 +2,21 @@ import { PrismicPreview } from '@prismicio/next'; import { PrismicProvider } from '@prismicio/react'; import type { AppProps } from 'next/app'; import Link from 'next/link'; -import { useRouter } from 'next/router'; import { DefaultSeo } from 'next-seo'; -import posthog from 'posthog-js'; import { PostHogProvider } from 'posthog-js/react'; -import { useEffect } from 'react'; import { Footer } from '../components/common/Footer'; import { Header } from '../components/common/Header'; import { Layout } from '../components/common/Layout'; import { Main } from '../components/common/Main'; +import { PostHogTracker } from '../hooks/usePostHog'; import { repositoryName } from '../prismicConfiguration'; import '../styles/index.scss'; import { linkResolver } from '../utils/prismic/helpers'; -if (typeof window !== 'undefined') { - posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY ?? '', { - api_host: - process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://app.posthog.com', - // Enable debug mode in development - loaded: posthog => { - if (process.env.NODE_ENV === 'development') posthog.debug(); - }, - capture_pageview: false, // Disable automatic pageview capture, as we capture manually - }); -} - const App = ({ Component, pageProps }: AppProps) => { - const router = useRouter(); - - useEffect(() => { - // Track page views - const handleRouteChange = () => posthog?.capture('$pageview'); - router.events.on('routeChangeComplete', handleRouteChange); - - return () => { - router.events.off('routeChangeComplete', handleRouteChange); - }; - }, []); return ( + (