useDataLoader.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { useCallback, useEffect } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { API, processModelsData, processGroupsData } from '../helpers';
  4. import { API_ENDPOINTS } from '../constants/playground.constants';
  5. export const useDataLoader = (
  6. userState,
  7. inputs,
  8. handleInputChange,
  9. setModels,
  10. setGroups
  11. ) => {
  12. const { t } = useTranslation();
  13. const loadModels = useCallback(async () => {
  14. try {
  15. const res = await API.get(API_ENDPOINTS.USER_MODELS);
  16. const { success, message, data } = res.data;
  17. if (success) {
  18. const { modelOptions, selectedModel } = processModelsData(data, inputs.model);
  19. setModels(modelOptions);
  20. if (selectedModel !== inputs.model) {
  21. handleInputChange('model', selectedModel);
  22. }
  23. } else {
  24. showError(t(message));
  25. }
  26. } catch (error) {
  27. showError(t('加载模型失败'));
  28. }
  29. }, [inputs.model, handleInputChange, setModels, t]);
  30. const loadGroups = useCallback(async () => {
  31. try {
  32. const res = await API.get(API_ENDPOINTS.USER_GROUPS);
  33. const { success, message, data } = res.data;
  34. if (success) {
  35. const userGroup = userState?.user?.group || JSON.parse(localStorage.getItem('user'))?.group;
  36. const groupOptions = processGroupsData(data, userGroup);
  37. setGroups(groupOptions);
  38. const hasCurrentGroup = groupOptions.some(option => option.value === inputs.group);
  39. if (!hasCurrentGroup) {
  40. handleInputChange('group', groupOptions[0]?.value || '');
  41. }
  42. } else {
  43. showError(t(message));
  44. }
  45. } catch (error) {
  46. showError(t('加载分组失败'));
  47. }
  48. }, [userState, inputs.group, handleInputChange, setGroups, t]);
  49. // 自动加载数据
  50. useEffect(() => {
  51. if (userState?.user) {
  52. loadModels();
  53. loadGroups();
  54. }
  55. }, [userState?.user, loadModels, loadGroups]);
  56. return {
  57. loadModels,
  58. loadGroups
  59. };
  60. };