| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- import { fetchMyAvatars, TAvatarItem } from "@/service/storage";
- import { isSuccess } from "@/utils";
- import { useState, useCallback } from "react";
- export const useAvatars = (initPageSize: number = 20) => {
- const [avatars, setAvatars] = useState<TAvatarItem[]>([]);
- const [pageIndex, setPageIndex] = useState(1);
- const [pageSize] = useState(initPageSize);
- const [totalCount, setTotalCount] = useState(0);
- const [isLoading, setIsLoading] = useState(false);
- const [hasMore, setHasMore] = useState(true);
- const loadAvatars = useCallback(async (reset: boolean = false) => {
- if (isLoading) return;
- setIsLoading(true);
- const currentPage = reset ? 1 : pageIndex;
- try {
- const response = await fetchMyAvatars({ pageSize, pageIndex: currentPage });
- if (isSuccess(response.status)) {
- const { data, totalCount: total } = response.data;
- setTotalCount(total);
- if (reset) {
- setAvatars(data);
- } else {
- setAvatars(prev => [...prev, ...data]);
- }
- setHasMore((currentPage * pageSize) < total);
- setPageIndex(currentPage + 1);
- }
- } finally {
- setIsLoading(false);
- }
- }, [isLoading, pageIndex, pageSize]);
- const resetAvatars = useCallback(() => {
- setAvatars([]);
- setPageIndex(1);
- setTotalCount(0);
- setHasMore(true);
- }, []);
- // 首次加载
- const initLoad = useCallback(async () => {
- resetAvatars();
- await loadAvatars(true);
- }, [resetAvatars, loadAvatars]);
- return {
- avatars,
- isLoading,
- hasMore,
- totalCount,
- loadAvatars,
- resetAvatars,
- initLoad,
- };
- };
|