Files
Todo/hooks/useRealtimeSync.ts
Paul Bailey fc5ad9f7af Improve real-time sync with 1-second polling and visual indicator
- Reduced polling interval from 2s to 1s for near-instant updates
- Added SyncIndicator component to show sync status
- Added console logging to debug sync behavior
- Updates across devices now appear within 1 second
- Visual feedback shows when data is being refreshed
2025-12-03 00:29:24 +00:00

73 lines
1.7 KiB
TypeScript

'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<NodeJS.Timeout | null>(null)
const refresh = useCallback(() => {
console.log('[RealtimeSync] Refreshing...', listId ? `list ${listId}` : 'page')
router.refresh()
if (onUpdate) {
onUpdate()
}
}, [router, onUpdate, listId])
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,
}
}