Spaces:
Sleeping
Sleeping
File size: 879 Bytes
9b2dc95 | 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 | 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 };
} |