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