46 lines
1.1 KiB
TypeScript
46 lines
1.1 KiB
TypeScript
import { useState, useEffect } from 'react';
|
|
import { fetchDictItemsByTypeCode } from '../api/dict';
|
|
import { SysDictItem } from '../types';
|
|
|
|
const dictCache: Record<string, SysDictItem[]> = {};
|
|
const pendingRequests: Record<string, Promise<SysDictItem[]>[]> = {};
|
|
|
|
export function useDict(typeCode: string) {
|
|
const [items, setItems] = useState<SysDictItem[]>(dictCache[typeCode] || []);
|
|
const [loading, setLoading] = useState(!dictCache[typeCode]);
|
|
|
|
useEffect(() => {
|
|
if (dictCache[typeCode]) {
|
|
setItems(dictCache[typeCode]);
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
|
|
let isMounted = true;
|
|
|
|
const load = async () => {
|
|
try {
|
|
const data = await fetchDictItemsByTypeCode(typeCode);
|
|
if (isMounted) {
|
|
dictCache[typeCode] = data;
|
|
setItems(data);
|
|
}
|
|
} catch (e) {
|
|
console.error(`Failed to fetch dictionary ${typeCode}:`, e);
|
|
} finally {
|
|
if (isMounted) {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
};
|
|
|
|
load();
|
|
|
|
return () => {
|
|
isMounted = false;
|
|
};
|
|
}, [typeCode]);
|
|
|
|
return { items, loading };
|
|
}
|