SpaceProbe1 / frontend /src /hooks /usePolling.ts
a9's picture
Upload 27 files
9b2dc95 verified
raw
history blame contribute delete
879 Bytes
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 };
}