fix(frontend): Sync client PostHog opt-in status with server setting (#11728)

This commit is contained in:
sp.wack 2025-11-13 17:22:05 +04:00 committed by GitHub
parent b605c96796
commit d5b2d2ebc5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,41 @@
import React from "react";
import { usePostHog } from "posthog-js/react";
import { handleCaptureConsent } from "#/utils/handle-capture-consent";
import { useSettings } from "./query/use-settings";
/**
* Hook to sync PostHog opt-in/out state with backend setting on mount.
* This ensures that if the backend setting changes (e.g., via API or different client),
* the PostHog instance reflects the current user preference.
*/
export const useSyncPostHogConsent = () => {
const posthog = usePostHog();
const { data: settings } = useSettings();
const hasSyncedRef = React.useRef(false);
React.useEffect(() => {
// Only run once when both PostHog and settings are available
if (!posthog || settings === undefined || hasSyncedRef.current) {
return;
}
const backendConsent = settings.USER_CONSENTS_TO_ANALYTICS;
// Only sync if there's a backend preference set
if (backendConsent !== null) {
const posthogHasOptedIn = posthog.has_opted_in_capturing();
const posthogHasOptedOut = posthog.has_opted_out_capturing();
// Check if PostHog state is out of sync with backend
const needsSync =
(backendConsent === true && !posthogHasOptedIn) ||
(backendConsent === false && !posthogHasOptedOut);
if (needsSync) {
handleCaptureConsent(posthog, backendConsent);
}
hasSyncedRef.current = true;
}
}, [posthog, settings]);
};

View File

@ -25,6 +25,7 @@ import { useIsOnTosPage } from "#/hooks/use-is-on-tos-page";
import { useAutoLogin } from "#/hooks/use-auto-login";
import { useAuthCallback } from "#/hooks/use-auth-callback";
import { useReoTracking } from "#/hooks/use-reo-tracking";
import { useSyncPostHogConsent } from "#/hooks/use-sync-posthog-consent";
import { LOCAL_STORAGE_KEYS } from "#/utils/local-storage";
import { EmailVerificationGuard } from "#/components/features/guards/email-verification-guard";
import { MaintenanceBanner } from "#/components/features/maintenance/maintenance-banner";
@ -100,6 +101,9 @@ export default function MainApp() {
// Initialize Reo.dev tracking in SaaS mode
useReoTracking();
// Sync PostHog opt-in/out state with backend setting on mount
useSyncPostHogConsent();
React.useEffect(() => {
// Don't change language when on TOS page
if (!isOnTosPage && settings?.LANGUAGE) {