58 lines
1.6 KiB
TypeScript
58 lines
1.6 KiB
TypeScript
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())
|
||
};
|
||
} |