Files
digital-pilates/hooks/useActiveCalories.ts
2025-09-24 09:43:17 +08:00

58 lines
1.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import dayjs from 'dayjs';
import { useCallback, useEffect, useState } from 'react';
import { NativeModules } from 'react-native';
const { HealthKitManager } = NativeModules;
type HealthDataOptions = {
startDate: string;
endDate: string;
};
/**
* 专用于获取运动消耗卡路里的hook
* 避免使用完整的healthData对象提升性能
*/
export function useActiveCalories(selectedDate?: Date) {
const [activeCalories, setActiveCalories] = useState<number>(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const fetchActiveCalories = useCallback(async (date: Date) => {
try {
setLoading(true);
setError(null);
const options: HealthDataOptions = {
startDate: dayjs(date).startOf('day').toDate().toISOString(),
endDate: dayjs(date).endOf('day').toDate().toISOString()
};
const result = await HealthKitManager.getActiveEnergyBurned(options);
if (result && result.totalValue !== undefined) {
setActiveCalories(Math.round(result.totalValue));
} else {
setActiveCalories(0);
}
} catch (err) {
console.error('获取运动消耗卡路里失败:', err);
setError(err instanceof Error ? err.message : '获取运动消耗卡路里失败');
setActiveCalories(0);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
const targetDate = selectedDate || new Date();
fetchActiveCalories(targetDate);
}, [selectedDate, fetchActiveCalories]);
return {
activeCalories,
loading,
error,
refetch: () => fetchActiveCalories(selectedDate || new Date())
};
}