fix: improve Analytics component; wrap it in Suspense boundary

This commit is contained in:
Dorian Niemiec 2024-09-08 15:17:26 +02:00
parent dcaa81707b
commit ea521a09c3
3 changed files with 22 additions and 22 deletions

View file

@ -56,7 +56,7 @@ export default function RootLayout({
>
{children}
<Toaster />
<Analytics />
<Analytics pagesRouter={false} />
</ThemeProvider>
</body>
</html>

View file

@ -1,36 +1,28 @@
"use client";
import { useEffect } from "react";
import { useEffect, Suspense } from "react";
import { usePathname, useSearchParams } from "next/navigation";
const MATOMO_URL = `${process.env.NEXT_PUBLIC_MATOMO_URL}`;
const MATOMO_SITE_ID = `${process.env.NEXT_PUBLIC_MATOMO_SITE_ID}`;
let firstUseEffect = true;
let firstUseEffect2 = true;
let secondUseEffect2 = true;
export default function AuthProvider() {
function AnalyticsInternal(props: { pagesRouter?: boolean }) {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (firstUseEffect) {
firstUseEffect = false;
} else {
if (firstUseEffect2) {
firstUseEffect2 = false;
return;
}
if (secondUseEffect2) {
secondUseEffect2 = false;
return;
if (props.pagesRouter) return;
}
// Track page view
const _paq = ((window as any)._paq = (window as any)._paq || []);
_paq.push(["setDocumentTitle", document.title]);
_paq.push(["trackPageView"]);
}, [pathname, searchParams]);
useEffect(() => {
if (firstUseEffect) {
firstUseEffect = false;
} else {
return;
}
@ -51,7 +43,15 @@ export default function AuthProvider() {
g.src = u + "matomo.js";
(s.parentNode as ParentNode).insertBefore(g, s);
})();
}, []);
}, [pathname, searchParams]);
return null;
}
export default function Analytics(props: { pagesRouter?: boolean }) {
return (
<Suspense>
<AnalyticsInternal {...props} />
</Suspense>
);
}

View file

@ -18,7 +18,7 @@ function MyApp({ Component, pageProps }: AppProps) {
`}</style>
<div className={`antialiased ${poppins.className}`}>
<Component {...pageProps} />
<Analytics />
<Analytics pagesRouter={true} />
</div>
</>
);