All files / app/(tabs)/collect/hooks useCollectData.ts

74.07% Statements 40/54
47.05% Branches 8/17
81.81% Functions 9/11
74.07% Lines 40/54

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140                          5x 5x 5x 5x 5x 5x     5x 2x 2x 2x   2x 2x 2x 1x 1x 1x           2x         5x 2x         2x       5x   2x   2x 2x                 5x                       5x 1x                   1x 1x 1x   1x 1x 1x 1x     1x                             5x   1x 1x       1x               5x                    
import { useCallback, useEffect, useRef, useState } from 'react';
import { useRouter } from 'expo-router';
import { useFocusEffect } from '@react-navigation/native';
 
import { supabaseCatfoodService } from '@/src/lib/supabase';
import type { CatfoodFavorite } from '@/src/types/collect';
import { appEvents, APP_EVENTS } from '@/src/utils';
import { showAlert, toast } from '@/src/components/dialogs';
 
/**
 * 收藏数据管理 Hook
 */
export function useCollectData() {
  const router = useRouter();
  const [favorites, setFavorites] = useState<CatfoodFavorite[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const isFirstLoad = useRef(true);
 
  // 获取收藏列表
  const fetchFavorites = useCallback(async (showLoading = true) => {
    try {
      Eif (showLoading) {
        setIsLoading(true);
      }
      setError(null);
      const result = await supabaseCatfoodService.getUserFavorites();
      if (result.data) {
        setFavorites(result.data as CatfoodFavorite[]);
      } else Eif (result.error) {
        setError(result.error.message);
      }
    } catch (err) {
      console.error('获取收藏列表失败:', err);
      setError('获取收藏列表失败');
    } finally {
      setIsLoading(false);
    }
  }, []);
 
  // 监听收藏变更事件
  useEffect(() => {
    const unsubscribe = appEvents.on(APP_EVENTS.FAVORITE_CHANGED, () => {
      // 收藏变更时静默刷新列表
      fetchFavorites(false);
    });
 
    return unsubscribe;
  }, [fetchFavorites]);
 
  // 页面获得焦点时刷新数据(从详情页返回时自动更新)
  useFocusEffect(
    useCallback(() => {
      if (isFirstLoad.current) {
        // 首次加载显示 loading
        fetchFavorites(true);
        isFirstLoad.current = false;
      } else E{
        // 后续获得焦点时静默刷新
        fetchFavorites(false);
      }
    }, [fetchFavorites])
  );
 
  // 下拉刷新
  const handleRefresh = useCallback(async () => {
    setRefreshing(true);
    try {
      await fetchFavorites(false);
    } catch (_err) {
      toast.error('刷新失败', '请检查网络连接后重试');
    } finally {
      setRefreshing(false);
    }
  }, [fetchFavorites]);
 
  // 删除收藏
  const handleDelete = useCallback((favoriteId: string, catfoodId: string) => {
    showAlert({
      title: '确认取消收藏',
      message: '您确定要取消收藏吗?',
      type: 'warning',
      buttons: [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          style: 'destructive',
          onPress: async () => {
            try {
              const result = await supabaseCatfoodService.toggleFavorite(catfoodId);
              if (result.data) {
                // 乐观更新:从列表中移除对应的项
                setFavorites((prev) => {
                  return prev.filter((fav: any) => {
                    const favId = fav.catfoodId || fav.id;
                    return favId?.toString() !== catfoodId?.toString();
                  });
                });
                toast.success('已取消收藏');
              } else E{
                toast.error('取消收藏失败', result.error?.message || '请重试');
              }
            } catch (err) {
              toast.error('取消收藏失败', '请重试');
              console.error('删除收藏失败:', err);
            }
          },
        },
      ],
    });
  }, []);
 
  // 点击收藏项,跳转到详情页
  const handlePress = useCallback(
    (catfoodId: string) => {
      console.log('点击收藏项,跳转到详情页:', catfoodId);
      Iif (!catfoodId) {
        console.error('catfoodId 为空');
        return;
      }
      router.push({
        pathname: '/detail',
        params: { id: catfoodId },
      } as any);
    },
    [router]
  );
 
  return {
    favorites,
    isLoading,
    error,
    refreshing,
    handleRefresh,
    handleDelete,
    handlePress,
  };
}