Split multi-hook frontend modules into single-hook files
This commit is contained in:
77
frontend/src/hooks/useJailConfigs.ts
Normal file
77
frontend/src/hooks/useJailConfigs.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* React hook for loading the jail config inventory.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { fetchJailConfigs, reloadConfig, updateJailConfig } from "../api/config";
|
||||
import { handleFetchError } from "../utils/fetchError";
|
||||
import type { JailConfig, JailConfigUpdate } from "../types/config";
|
||||
|
||||
export interface UseJailConfigsResult {
|
||||
jails: JailConfig[];
|
||||
total: number;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refresh: () => void;
|
||||
updateJail: (name: string, update: JailConfigUpdate) => Promise<void>;
|
||||
reloadAll: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all jail configs and expose update controls.
|
||||
*/
|
||||
export function useJailConfigs(): UseJailConfigsResult {
|
||||
const [jails, setJails] = useState<JailConfig[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const load = useCallback((): void => {
|
||||
abortRef.current?.abort();
|
||||
const ctrl = new AbortController();
|
||||
abortRef.current = ctrl;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
fetchJailConfigs()
|
||||
.then((resp) => {
|
||||
if (!ctrl.signal.aborted) {
|
||||
setJails(resp.jails);
|
||||
setTotal(resp.total);
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!ctrl.signal.aborted) {
|
||||
handleFetchError(err, setError, "Failed to fetch jail configs");
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!abortRef.current?.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
return (): void => {
|
||||
abortRef.current?.abort();
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const updateJail = useCallback(
|
||||
async (name: string, update: JailConfigUpdate): Promise<void> => {
|
||||
await updateJailConfig(name, update);
|
||||
load();
|
||||
},
|
||||
[load],
|
||||
);
|
||||
|
||||
const reloadAll = useCallback(async (): Promise<void> => {
|
||||
await reloadConfig();
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
return { jails, total, loading, error, refresh: load, updateJail, reloadAll };
|
||||
}
|
||||
Reference in New Issue
Block a user