Files
ai-wpa/components/topics/ViewTracker.tsx
2025-08-30 18:18:57 +05:30

41 lines
1.0 KiB
TypeScript

'use client'
import { useEffect, useRef } from 'react'
interface ViewTrackerProps {
topicSlug: string
enabled?: boolean // Allow disabling for drafts or other cases
}
export function ViewTracker({ topicSlug, enabled = true }: ViewTrackerProps) {
const hasTracked = useRef(false)
useEffect(() => {
if (!enabled || hasTracked.current || !topicSlug) {
return
}
const trackView = async () => {
try {
await fetch(`/api/topics/${encodeURIComponent(topicSlug)}/view`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
hasTracked.current = true
} catch (error) {
console.warn('Failed to track topic view:', error)
}
}
// Track view after a short delay to ensure the user actually viewed the post
const timer = setTimeout(trackView, 2000)
return () => {
clearTimeout(timer)
}
}, [topicSlug, enabled])
// This component doesn't render anything
return null
}