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

51 lines
1.3 KiB
JavaScript
Raw 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);
// 获取数据字典
const getDictionary = (options) => {
if (!options)
throw new Error("请传入 options");
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(() => {
setLoading(false);
});
});
};
if (returnType === "array")
return [loading, getDictionary];
return { loading, getDictionary };
}
export default useDictionary;