arbret/frontend/app/exchange/hooks/useExchangePrice.ts

74 lines
2 KiB
TypeScript
Raw Normal View History

import { useState, useEffect, useCallback } from "react";
import { exchangeApi } from "../../api";
import { components } from "../../generated/api";
type ExchangePriceResponse = components["schemas"]["ExchangePriceResponse"];
interface UseExchangePriceOptions {
/** Whether the user is authenticated and authorized */
enabled?: boolean;
/** Auto-refresh interval in milliseconds (default: 60000) */
refreshInterval?: number;
}
interface UseExchangePriceResult {
priceData: ExchangePriceResponse | null;
isLoading: boolean;
error: string | null;
lastUpdate: Date | null;
refetch: () => Promise<void>;
}
/**
* Hook for fetching and managing exchange price data.
* Automatically refreshes price data at specified intervals.
*/
export function useExchangePrice(options: UseExchangePriceOptions = {}): UseExchangePriceResult {
const { enabled = true, refreshInterval = 60000 } = options;
const [priceData, setPriceData] = useState<ExchangePriceResponse | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
const fetchPrice = useCallback(async () => {
if (!enabled) return;
setIsLoading(true);
setError(null);
try {
const data = await exchangeApi.getPrice();
setPriceData(data);
setLastUpdate(new Date());
if (data.error) {
setError(data.error);
}
if (data.price?.is_stale) {
setError("Price is stale. Trade booking may be blocked.");
}
} catch (err) {
console.error("Failed to fetch price:", err);
setError("Failed to load price data");
} finally {
setIsLoading(false);
}
}, [enabled]);
useEffect(() => {
if (!enabled) return;
fetchPrice();
const interval = setInterval(fetchPrice, refreshInterval);
return () => clearInterval(interval);
}, [enabled, fetchPrice, refreshInterval]);
return {
priceData,
isLoading,
error,
lastUpdate,
refetch: fetchPrice,
};
}