fix(blog): prevent duplicate blog_post_time_spent events

- Add trackedTimeSpent ref to track if time-spent event already fired
- Check flag in visibilitychange handler and cleanup function
- Remove duplicate interface declaration in BlogPostAnalyticsProps
- Remove duplicate BlogPostAnalytics component opening tag
This commit is contained in:
Roo Code 2026-01-28 00:44:40 +00:00
parent 610599fee8
commit 2528775815
2 changed files with 9 additions and 6 deletions

View file

@ -89,7 +89,6 @@ export default async function BlogPostPage({ params }: BlogPostPageProps) {
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }} />
{/* PostHog Analytics */}
<BlogPostAnalytics
<BlogPostAnalytics
post={{
slug: post.slug,

View file

@ -25,7 +25,6 @@ export function BlogIndexAnalytics({ postCount }: BlogIndexAnalyticsProps) {
return null
}
interface BlogPostAnalyticsProps {
interface BlogPostAnalyticsProps {
post: {
slug: string
@ -44,6 +43,7 @@ interface BlogPostAnalyticsProps {
export function BlogPostAnalytics({ post }: BlogPostAnalyticsProps) {
const trackedView = useRef(false)
const trackedDepths = useRef<Set<25 | 50 | 75 | 100>>(new Set())
const trackedTimeSpent = useRef(false)
const startTime = useRef<number>(Date.now())
useEffect(() => {
@ -74,7 +74,8 @@ export function BlogPostAnalytics({ post }: BlogPostAnalyticsProps) {
// Track time spent on page when leaving
const handleVisibilityChange = () => {
if (document.visibilityState === "hidden") {
if (document.visibilityState === "hidden" && !trackedTimeSpent.current) {
trackedTimeSpent.current = true
const timeSpent = Date.now() - effectStartTime
trackBlogPostTimeSpent(post as BlogPost, timeSpent)
}
@ -90,9 +91,12 @@ export function BlogPostAnalytics({ post }: BlogPostAnalyticsProps) {
window.removeEventListener("scroll", handleScroll)
document.removeEventListener("visibilitychange", handleVisibilityChange)
// Track time spent when component unmounts
const timeSpent = Date.now() - effectStartTime
trackBlogPostTimeSpent(post as BlogPost, timeSpent)
// Track time spent when component unmounts (only if not already tracked)
if (!trackedTimeSpent.current) {
trackedTimeSpent.current = true
const timeSpent = Date.now() - effectStartTime
trackBlogPostTimeSpent(post as BlogPost, timeSpent)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [post.slug])