/ chandeskpro / src / hooks / useAutoRefresh.ts
swadhinbiswas Initial release v0.1.0 · 1/16/2026
ed7a4e4
49 lines · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { useEffect, useRef } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useSettingsStore } from '../stores/settingsStore'

interface UseAutoRefreshProps {
    board: string | null
    threadId: number | null
}

export function useAutoRefresh({ board, threadId }: UseAutoRefreshProps) {
    const queryClient = useQueryClient()
    const { autoRefreshEnabled, autoRefreshInterval } = useSettingsStore()
    const intervalRef = useRef<NodeJS.Timeout | null>(null)

    useEffect(() => {
        if (!autoRefreshEnabled || !board) {
            if (intervalRef.current) {
                clearInterval(intervalRef.current)
                intervalRef.current = null
            }
            return
        }

        // Refresh function
        const refresh = () => {
            if (threadId) {
                // Refresh thread
                queryClient.invalidateQueries({ queryKey: ['thread', board, threadId] })
                console.log(`[Auto-Refresh] Refreshed thread ${threadId} on /${board}/`)
            } else {
                // Refresh catalog
                queryClient.invalidateQueries({ queryKey: ['catalog', board] })
                console.log(`[Auto-Refresh] Refreshed catalog for /${board}/`)
            }
        }

        // Set up interval
        intervalRef.current = setInterval(refresh, autoRefreshInterval * 1000)

        // Cleanup
        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current)
                intervalRef.current = null
            }
        }
    }, [board, threadId, autoRefreshEnabled, autoRefreshInterval, queryClient])
}