xref: /MusicFree/src/pages/topList/hooks/useGetTopList.ts (revision d52aa40ee35db6a95adf7802ea10540bf51594a8)
1*d52aa40eS猫头猫import {RequestStateCode} from '@/constants/commonConst';
2*d52aa40eS猫头猫import PluginManager from '@/core/pluginManager';
3*d52aa40eS猫头猫import produce from 'immer';
4*d52aa40eS猫头猫import {useAtom} from 'jotai';
5*d52aa40eS猫头猫import {useCallback} from 'react';
6*d52aa40eS猫头猫import {pluginsTopListAtom} from '../store/atoms';
7*d52aa40eS猫头猫
8*d52aa40eS猫头猫export default function useGetTopList() {
9*d52aa40eS猫头猫    const [pluginsTopList, setPluginsTopList] = useAtom(pluginsTopListAtom);
10*d52aa40eS猫头猫
11*d52aa40eS猫头猫    const getTopList = useCallback(
12*d52aa40eS猫头猫        async (pluginHash: string) => {
13*d52aa40eS猫头猫            try {
14*d52aa40eS猫头猫                // 有数据/加载中直接返回
15*d52aa40eS猫头猫                if (
16*d52aa40eS猫头猫                    pluginsTopList[pluginHash]?.data?.length ||
17*d52aa40eS猫头猫                    pluginsTopList[pluginHash]?.state ===
18*d52aa40eS猫头猫                        RequestStateCode.PENDING
19*d52aa40eS猫头猫                ) {
20*d52aa40eS猫头猫                    return;
21*d52aa40eS猫头猫                }
22*d52aa40eS猫头猫                // 获取plugin
23*d52aa40eS猫头猫                const plugin = PluginManager.getByHash(pluginHash);
24*d52aa40eS猫头猫                if (!plugin) {
25*d52aa40eS猫头猫                    return;
26*d52aa40eS猫头猫                }
27*d52aa40eS猫头猫
28*d52aa40eS猫头猫                setPluginsTopList(
29*d52aa40eS猫头猫                    produce(draft => {
30*d52aa40eS猫头猫                        draft[pluginHash] = {
31*d52aa40eS猫头猫                            state: RequestStateCode.PENDING,
32*d52aa40eS猫头猫                            data: [],
33*d52aa40eS猫头猫                        };
34*d52aa40eS猫头猫                    }),
35*d52aa40eS猫头猫                );
36*d52aa40eS猫头猫                const result = await plugin?.methods?.getTopLists();
37*d52aa40eS猫头猫                setPluginsTopList(
38*d52aa40eS猫头猫                    produce(draft => {
39*d52aa40eS猫头猫                        draft[pluginHash] = {
40*d52aa40eS猫头猫                            data: result,
41*d52aa40eS猫头猫                            state: RequestStateCode.FINISHED,
42*d52aa40eS猫头猫                        };
43*d52aa40eS猫头猫                    }),
44*d52aa40eS猫头猫                );
45*d52aa40eS猫头猫            } catch {
46*d52aa40eS猫头猫                setPluginsTopList(
47*d52aa40eS猫头猫                    produce(draft => {
48*d52aa40eS猫头猫                        draft[pluginHash].state = RequestStateCode.FINISHED;
49*d52aa40eS猫头猫                    }),
50*d52aa40eS猫头猫                );
51*d52aa40eS猫头猫            }
52*d52aa40eS猫头猫        },
53*d52aa40eS猫头猫        [pluginsTopList],
54*d52aa40eS猫头猫    );
55*d52aa40eS猫头猫
56*d52aa40eS猫头猫    return getTopList;
57*d52aa40eS猫头猫}
58