useAvatars.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { fetchMyAvatars, TAvatarItem } from "@/service/storage";
  2. import { isSuccess } from "@/utils";
  3. import { useState, useCallback } from "react";
  4. export const useAvatars = (initPageSize: number = 20) => {
  5. const [avatars, setAvatars] = useState<TAvatarItem[]>([]);
  6. const [pageIndex, setPageIndex] = useState(1);
  7. const [pageSize] = useState(initPageSize);
  8. const [totalCount, setTotalCount] = useState(0);
  9. const [isLoading, setIsLoading] = useState(false);
  10. const [hasMore, setHasMore] = useState(true);
  11. const loadAvatars = useCallback(async (reset: boolean = false) => {
  12. if (isLoading) return;
  13. setIsLoading(true);
  14. const currentPage = reset ? 1 : pageIndex;
  15. try {
  16. const response = await fetchMyAvatars({ pageSize, pageIndex: currentPage });
  17. if (isSuccess(response.status)) {
  18. const { data, totalCount: total } = response.data;
  19. setTotalCount(total);
  20. if (reset) {
  21. setAvatars(data);
  22. } else {
  23. setAvatars(prev => [...prev, ...data]);
  24. }
  25. setHasMore((currentPage * pageSize) < total);
  26. setPageIndex(currentPage + 1);
  27. }
  28. } finally {
  29. setIsLoading(false);
  30. }
  31. }, [isLoading, pageIndex, pageSize]);
  32. const resetAvatars = useCallback(() => {
  33. setAvatars([]);
  34. setPageIndex(1);
  35. setTotalCount(0);
  36. setHasMore(true);
  37. }, []);
  38. // 首次加载
  39. const initLoad = useCallback(async () => {
  40. resetAvatars();
  41. await loadAvatars(true);
  42. }, [resetAvatars, loadAvatars]);
  43. return {
  44. avatars,
  45. isLoading,
  46. hasMore,
  47. totalCount,
  48. loadAvatars,
  49. resetAvatars,
  50. initLoad,
  51. };
  52. };