All files / app/(tabs)/ranking/hooks useRankingData.ts

95.23% Statements 20/21
100% Branches 8/8
88.88% Functions 8/9
94.11% Lines 16/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                        5x 5x 5x 5x 5x     5x               5x   5x 4x         5x 1x       5x 2x 1x 1x       5x                    
import { useEffect } from 'react';
 
import { useAllCatFoods, useCatFoodStore } from '@/src/store/catFoodStore';
import { useCatfoodRealtime } from '@/src/hooks/useCatfoodRealtime';
 
/**
 * 排行榜数据管理 Hook
 * 负责猫粮数据的获取、刷新和加载更多
 * 包含实时数据同步功能
 */
export function useRankingData() {
  // 使用 catFoodStore - 使用选择器避免不必要的重渲染
  const { catfoods, isLoading, hasMore } = useAllCatFoods();
  const fetchCatFoods = useCatFoodStore((state) => state.fetchCatFoods);
  const isRefreshing = useCatFoodStore((state) => state.isRefreshing);
  const isLoadingMore = useCatFoodStore((state) => state.isLoadingMore);
  const pagination = useCatFoodStore((state) => state.pagination);
 
  // 🔥 启用实时订阅 - 监听所有猫粮的评分、点赞变化
  useCatfoodRealtime({
    enabled: true, // 排行榜页面始终启用实时同步
    onUpdate: (catfood) => {
      console.log('🔔 排行榜收到实时更新:', catfood.name);
    },
  });
 
  // 初始加载
  useEffect(() => {
    // 如果没有数据,则加载
    if (catfoods.length === 0 && !isLoading) {
      fetchCatFoods(1, true);
    }
  }, [catfoods.length, isLoading, fetchCatFoods]);
 
  // 下拉刷新
  const handleRefresh = async () => {
    await fetchCatFoods(1, true);
  };
 
  // 加载更多
  const handleLoadMore = () => {
    if (hasMore && !isLoadingMore) {
      const nextPage = pagination.all.page + 1;
      fetchCatFoods(nextPage, false);
    }
  };
 
  return {
    catfoods,
    isLoading,
    hasMore,
    isRefreshing,
    isLoadingMore,
    handleRefresh,
    handleLoadMore,
  };
}