✈️(frontend) pause Posthog when offline

Posthog keeps trying to send events when the user
is offline, causing the network request queue to fill up
and slowing down the app. This commit pauses Posthog
when the user is offline and resumes it when back online.
This commit is contained in:
Anthony LC
2025-12-22 09:50:05 +01:00
parent 78c7ab247b
commit e4b8ffb304
2 changed files with 15 additions and 5 deletions

View File

@@ -14,10 +14,8 @@ and this project adheres to
### Changed
- 🥅(frontend) intercept 401 error on GET threads #1754
## Changed
- 🦺(frontend) check content type pdf on PdfBlock #1756
- ✈️(frontend) pause Posthog when offline #1755
### Fixed

View File

@@ -3,6 +3,7 @@ import posthog from 'posthog-js';
import { PostHogProvider as PHProvider } from 'posthog-js/react';
import { JSX, PropsWithChildren, ReactNode, useEffect } from 'react';
import { useIsOffline } from '@/features/service-worker/hooks/useOffline';
import { AbstractAnalytic, AnalyticEvent } from '@/libs/';
export class PostHogAnalytic extends AbstractAnalytic {
@@ -45,6 +46,8 @@ export function PostHogProvider({
children,
conf,
}: PropsWithChildren<PostHogProviderProps>) {
const isOffline = useIsOffline((state) => state.isOffline);
useEffect(() => {
if (!conf?.id || !conf?.host || posthog.__loaded) {
return;
@@ -53,9 +56,9 @@ export function PostHogProvider({
posthog.init(conf.id, {
api_host: conf.host,
person_profiles: 'always',
loaded: (posthog) => {
loaded: (posthogInstance) => {
if (process.env.NODE_ENV === 'development') {
posthog.debug();
posthogInstance.debug();
}
},
capture_pageview: false,
@@ -71,5 +74,14 @@ export function PostHogProvider({
};
}, [conf?.host, conf?.id]);
// Disable PostHog when offline to prevent retry requests
useEffect(() => {
if (isOffline) {
posthog.opt_out_capturing();
} else {
posthog.opt_in_capturing();
}
}, [isOffline]);
return <PHProvider client={posthog}>{children}</PHProvider>;
}