initial commit
This commit is contained in:
41
components/topics/ViewTracker.tsx
Normal file
41
components/topics/ViewTracker.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
'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
|
||||
}
|
||||
Reference in New Issue
Block a user