Files
sam-react-prod/src/hooks/useStatsLoader.ts

49 lines
1.4 KiB
TypeScript
Raw Normal View History

import { useState, useEffect, useCallback, useRef } from 'react';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
/**
* Stats
*
* , , .
*
* @param loadFn - Stats API
* @param initialData - ( )
*
* @example
* // 기본 사용
* const { data: stats, reload: reloadStats } = useStatsLoader(getProcessStats);
*
* @example
* // 초기값 제공 (있으면 자동 로딩 스킵)
* const { data: stats, reload: reloadStats } = useStatsLoader(getContractStats, initialStats);
*/
export function useStatsLoader<T>(
loadFn: () => Promise<{ success: boolean; data?: T }>,
initialData?: T | null,
) {
const [data, setData] = useState<T | null>(initialData ?? null);
const loadFnRef = useRef(loadFn);
loadFnRef.current = loadFn;
const reload = useCallback(async () => {
try {
const result = await loadFnRef.current();
if (result.success && result.data) {
setData(result.data);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[useStatsLoader] error:', error);
}
}, []);
useEffect(() => {
if (initialData != null) return;
reload();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { data, setData, reload };
}