zy-react-library/hooks/useDictionary/index.js

61 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

import { request } from "@cqsjjb/jjb-common-lib/http";
import { useState } from "react";
import { DICTIONARY_APP_KEY_ENUM } from "../../enum/dictionary";
/**
* 获取数据字典
*/
function useDictionary(returnType = "object") {
// loading状态
const [loading, setLoading] = useState(false);
// 用于跟踪进行中的请求数量(不暴露给外部)
let requestCount = 0;
// 获取数据字典
const getDictionary = (options) => {
if (!options)
throw new Error("请传入 options");
// 增加请求数量并设置loading状态
requestCount++;
if (requestCount > 0) {
setLoading(true);
}
return new Promise((resolve, reject) => {
const { appKey = DICTIONARY_APP_KEY_ENUM.DEFAULT, dictValue } = options;
if (!Object.values(DICTIONARY_APP_KEY_ENUM).includes(appKey))
throw new Error("传入的 options.appKey 不在 DICTIONARY_APP_KEY_ENUM 中");
if (!dictValue)
throw new Error("请传入 options.dictValue");
// 发送请求
request(
"/config/dict-trees/list/by/dictValues",
"get",
{ appKey, dictValue },
)
.then((res) => {
resolve(res.data);
})
.catch((err) => {
reject(err);
})
.finally(() => {
// 减少请求数量并在没有进行中的请求时设置loading为false
requestCount--;
if (requestCount <= 0) {
setLoading(false);
}
});
});
};
if (returnType === "array")
return [loading, getDictionary];
return { loading, getDictionary };
}
export default useDictionary;