arbret/frontend/app/exchange/hooks/useExchangePrice.ts
counterweight a6fa6a8012
Refactor API layer into structured domain-specific modules
- Created new api/ directory with domain-specific API modules:
  - api/client.ts: Base API client with error handling
  - api/auth.ts: Authentication endpoints
  - api/exchange.ts: Exchange/price endpoints
  - api/trades.ts: User trade endpoints
  - api/profile.ts: Profile management endpoints
  - api/invites.ts: Invite endpoints
  - api/admin.ts: Admin endpoints
  - api/index.ts: Centralized exports

- Migrated all API calls from ad-hoc api.get/post/put to typed domain APIs
- Updated all imports across codebase
- Fixed test mocks to use new API structure
- Fixed type issues in validation utilities
- Removed old api.ts file

Benefits:
- Type-safe endpoints (no more string typos)
- Centralized API surface (easy to discover endpoints)
- Better organization (domain-specific modules)
- Uses generated OpenAPI types automatically
2025-12-25 20:32:11 +01:00

73 lines
2 KiB
TypeScript

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,
};
}