cosmo/frontend/src/hooks/useHistoricalData.ts

47 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-11-27 10:14:25 +00:00
/**
* Custom hook for fetching historical celestial data
*/
import { useState, useEffect, useCallback } from 'react';
import { fetchCelestialPositions } from '../utils/api';
import type { CelestialBody } from '../types';
export function useHistoricalData(selectedDate: Date | null) {
const [bodies, setBodies] = useState<CelestialBody[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const loadHistoricalData = useCallback(async (date: Date) => {
try {
setLoading(true);
setError(null);
// For historical data, we just need a single snapshot at the given date
// Set start and end to the same date, or use a small range
const startDate = new Date(date);
const endDate = new Date(date);
endDate.setDate(endDate.getDate() + 1); // Add 1 day to ensure valid range
const data = await fetchCelestialPositions(
startDate.toISOString(),
endDate.toISOString(),
'1d'
);
setBodies(data.bodies);
} catch (err) {
console.error('Failed to fetch historical data:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
if (selectedDate) {
loadHistoricalData(selectedDate);
}
}, [selectedDate, loadHistoricalData]);
return { bodies, loading, error };
}