Fix PostHog init race condition — remove __loaded guard
posthog.capture() queues events automatically before init completes, so checking __loaded blocked the first pageview from being sent. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -2,19 +2,22 @@
|
|||||||
|
|
||||||
import { useEffect } from 'react'
|
import { useEffect } from 'react'
|
||||||
import { usePathname } from 'next/navigation'
|
import { usePathname } from 'next/navigation'
|
||||||
import { initPostHog, posthog } from '@/lib/posthog'
|
import posthog from 'posthog-js'
|
||||||
|
|
||||||
export default function PostHogProvider({ children }: { children: React.ReactNode }) {
|
export default function PostHogProvider({ children }: { children: React.ReactNode }) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
initPostHog()
|
posthog.init('phc_BHgg9S7CQqVShe7EMCdi86PxA49qcNaTsR9Nn5EGxRCT', {
|
||||||
|
api_host: 'https://analytics.hyggecraftery.com',
|
||||||
|
capture_pageview: false,
|
||||||
|
persistence: 'localStorage',
|
||||||
|
})
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const pathname = usePathname()
|
const pathname = usePathname()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (posthog.__loaded) {
|
// PostHog queues events automatically before init completes
|
||||||
posthog.capture('$pageview', { $current_url: window.location.href })
|
posthog.capture('$pageview', { $current_url: window.location.href })
|
||||||
}
|
|
||||||
}, [pathname])
|
}, [pathname])
|
||||||
|
|
||||||
return <>{children}</>
|
return <>{children}</>
|
||||||
|
|||||||
@@ -1,13 +1,2 @@
|
|||||||
import posthog from 'posthog-js'
|
import posthog from 'posthog-js'
|
||||||
|
|
||||||
export function initPostHog() {
|
|
||||||
if (typeof window !== 'undefined' && !posthog.__loaded) {
|
|
||||||
posthog.init('phc_BHgg9S7CQqVShe7EMCdi86PxA49qcNaTsR9Nn5EGxRCT', {
|
|
||||||
api_host: 'https://analytics.hyggecraftery.com',
|
|
||||||
capture_pageview: false,
|
|
||||||
persistence: 'localStorage',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export { posthog }
|
export { posthog }
|
||||||
|
|||||||
Reference in New Issue
Block a user