Refactor frontend API calls into hooks and complete task states
This commit is contained in:
55
frontend/src/hooks/useMapColorThresholds.ts
Normal file
55
frontend/src/hooks/useMapColorThresholds.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { fetchMapColorThresholds, updateMapColorThresholds } from "../api/config";
|
||||
import type {
|
||||
MapColorThresholdsResponse,
|
||||
MapColorThresholdsUpdate,
|
||||
} from "../types/config";
|
||||
|
||||
export interface UseMapColorThresholdsResult {
|
||||
thresholds: MapColorThresholdsResponse | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refresh: () => Promise<void>;
|
||||
updateThresholds: (payload: MapColorThresholdsUpdate) => Promise<MapColorThresholdsResponse>;
|
||||
}
|
||||
|
||||
export function useMapColorThresholds(): UseMapColorThresholdsResult {
|
||||
const [thresholds, setThresholds] = useState<MapColorThresholdsResponse | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async (): Promise<void> => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const data = await fetchMapColorThresholds();
|
||||
setThresholds(data);
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : "Failed to fetch map color thresholds");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const updateThresholds = useCallback(
|
||||
async (payload: MapColorThresholdsUpdate): Promise<MapColorThresholdsResponse> => {
|
||||
const updated = await updateMapColorThresholds(payload);
|
||||
setThresholds(updated);
|
||||
return updated;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
thresholds,
|
||||
loading,
|
||||
error,
|
||||
refresh: load,
|
||||
updateThresholds,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user