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} {children}
<Toaster /> <Toaster />
<Analytics /> <Analytics pagesRouter={false} />
</ThemeProvider> </ThemeProvider>
</body> </body>
</html> </html>

View file

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