'use client' import { useEffect, useRef, useCallback } from 'react' import { useRouter } from 'next/navigation' interface UseRealtimeSyncOptions { listId?: string enabled?: boolean pollInterval?: number onUpdate?: () => void } /** * Hook to enable real-time synchronization of list data * Polls the server for updates by refreshing the route */ export function useRealtimeSync({ listId, enabled = true, pollInterval = 3000, // Poll every 3 seconds onUpdate }: UseRealtimeSyncOptions) { const router = useRouter() const intervalRef = useRef(null) const refresh = useCallback(() => { router.refresh() if (onUpdate) { onUpdate() } }, [router, onUpdate]) useEffect(() => { if (!enabled) { if (intervalRef.current) { clearInterval(intervalRef.current) intervalRef.current = null } return } // Start polling intervalRef.current = setInterval(refresh, pollInterval) // Cleanup on unmount return () => { if (intervalRef.current) { clearInterval(intervalRef.current) intervalRef.current = null } } }, [enabled, pollInterval, refresh]) // Also refresh when the page becomes visible again useEffect(() => { const handleVisibilityChange = () => { if (document.visibilityState === 'visible' && enabled) { refresh() } } document.addEventListener('visibilitychange', handleVisibilityChange) return () => { document.removeEventListener('visibilitychange', handleVisibilityChange) } }, [enabled, refresh]) return { refresh, } }