45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react';
|
|
|
|
type Fetcher<T> = (...args: any[]) => Promise<T>;
|
|
|
|
interface UseHybridBackendReturn<T> {
|
|
data: T | null;
|
|
isLoading: boolean;
|
|
error: Error | null;
|
|
refresh: () => void;
|
|
}
|
|
|
|
export function useHybridBackend<T>(
|
|
fetcher: Fetcher<T>,
|
|
deps: any[] = []
|
|
): UseHybridBackendReturn<T> {
|
|
const [data, setData] = useState<T | null>(null);
|
|
const [isLoading, setIsLoading] = useState<boolean>(true);
|
|
const [error, setError] = useState<Error | null>(null);
|
|
const [refreshCount, setRefreshCount] = useState(0);
|
|
|
|
const fetchData = useCallback(async () => {
|
|
setIsLoading(true);
|
|
setError(null);
|
|
try {
|
|
const result = await fetcher();
|
|
setData(result);
|
|
} catch (e) {
|
|
setError(e instanceof Error ? e : new Error('An unknown error occurred'));
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [...deps, refreshCount]);
|
|
|
|
useEffect(() => {
|
|
fetchData();
|
|
}, [fetchData]);
|
|
|
|
const refresh = () => {
|
|
setRefreshCount(prev => prev + 1);
|
|
};
|
|
|
|
return { data, isLoading, error, refresh };
|
|
}
|