Files
Todo/hooks/useRealtimeSync.ts
Paul Bailey 0fc8c719b9 Add real-time updates and fix delete button state
- Simplified useRealtimeSync to use router.refresh() polling
- Created RealtimeUpdater component for easy integration
- Added real-time updates to home page (3s polling)
- Fixed DeleteItemButton to properly reset state on error
- Updates now refresh every 3 seconds and on window focus
- Changes from other users/browsers will appear quickly
2025-12-02 14:29:28 +00:00

72 lines
1.6 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(() => {
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,
}
}