Spaces:
Sleeping
Sleeping
| import { useState, useEffect, useCallback } from 'react'; | |
| const API_BASE = '/api'; | |
| export function usePolling<T>( | |
| fetchFn: () => Promise<T>, | |
| interval: number = 5000, | |
| enabled: boolean = true | |
| ) { | |
| const [data, setData] = useState<T | null>(null); | |
| const [loading, setLoading] = useState(true); | |
| const [error, setError] = useState<string | null>(null); | |
| const fetch = useCallback(async () => { | |
| try { | |
| const result = await fetchFn(); | |
| setData(result); | |
| setError(null); | |
| } catch (err) { | |
| setError(err instanceof Error ? err.message : 'Unknown error'); | |
| } finally { | |
| setLoading(false); | |
| } | |
| }, [fetchFn]); | |
| useEffect(() => { | |
| if (!enabled) return; | |
| fetch(); | |
| const id = setInterval(fetch, interval); | |
| return () => clearInterval(id); | |
| }, [fetch, interval, enabled]); | |
| return { data, loading, error, refetch: fetch }; | |
| } |