All files / hooks useFavorite.ts

100% Statements 14/14
100% Branches 7/7
100% Functions 2/2
100% Lines 13/13

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                                                                      16x 16x     16x 6x   4x 4x 4x 3x 3x   1x 1x   4x       16x              
/**
 * 收藏功能 Hook
 */
 
import { useCallback, useState } from 'react';
import { Alert } from 'react-native';
 
import { aiReportService } from '@/src/services/api';
import { logger } from '@/src/utils/logger';
 
interface UseFavoriteOptions {
  /** 猫粮 ID(用于收藏) */
  catfoodId?: number;
  /** 初始收藏状态 */
  initialFavorited?: boolean;
}
 
interface UseFavoriteReturn {
  /** 是否已收藏 */
  isFavorited: boolean;
  /** 是否正在切换 */
  isToggling: boolean;
  /** 切换收藏状态 */
  toggle: () => Promise<void>;
  /** 手动设置收藏状态 */
  setFavorited: (value: boolean) => void;
}
 
/**
 * 收藏功能 Hook
 */
export function useFavorite({
  catfoodId,
  initialFavorited = false,
}: UseFavoriteOptions): UseFavoriteReturn {
  const [isFavorited, setIsFavorited] = useState(initialFavorited);
  const [isToggling, setIsToggling] = useState(false);
 
  // 切换收藏
  const toggle = useCallback(async () => {
    if (!catfoodId || isToggling) return;
 
    setIsToggling(true);
    try {
      const result = await aiReportService.toggleFavoriteReport(catfoodId);
      setIsFavorited(result.favorited);
      Alert.alert('✅ 成功', result.favorited ? '已收藏此报告' : '已取消收藏');
    } catch (error) {
      logger.error('切换收藏失败', error as Error);
      Alert.alert('❌ 失败', '操作失败,请重试');
    } finally {
      setIsToggling(false);
    }
  }, [catfoodId, isToggling]);
 
  return {
    isFavorited,
    isToggling,
    toggle,
    setFavorited: setIsFavorited,
  };
}