Fix jail banned IP loading race with AbortController
This commit is contained in:
@@ -18,6 +18,7 @@ describe("useJailBannedIps", () => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
expect(result.current.items.length).toBe(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith("sshd", 1, 25, undefined, expect.any(AbortSignal));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.unban("1.2.3.4");
|
||||
|
||||
@@ -34,8 +34,14 @@ export function useJailBannedIps(jailName: string): UseJailBannedIpsResult {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [opError, setOpError] = useState<string | null>(null);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const load = useCallback(async (): Promise<void> => {
|
||||
abortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
const { signal } = controller;
|
||||
|
||||
if (!jailName) {
|
||||
setItems([]);
|
||||
setTotal(0);
|
||||
@@ -47,13 +53,27 @@ export function useJailBannedIps(jailName: string): UseJailBannedIpsResult {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const resp = await fetchJailBannedIps(jailName, page, pageSize, debouncedSearch || undefined);
|
||||
const resp = await fetchJailBannedIps(
|
||||
jailName,
|
||||
page,
|
||||
pageSize,
|
||||
debouncedSearch || undefined,
|
||||
signal,
|
||||
);
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
setItems(resp.items);
|
||||
setTotal(resp.total);
|
||||
} catch (err: unknown) {
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
handleFetchError(err, setError, "Failed to fetch jailed IPs");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (!signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [jailName, page, pageSize, debouncedSearch]);
|
||||
|
||||
@@ -76,6 +96,10 @@ export function useJailBannedIps(jailName: string): UseJailBannedIpsResult {
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
|
||||
return (): void => {
|
||||
abortRef.current?.abort();
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const unban = useCallback(async (ip: string): Promise<void> => {
|
||||
|
||||
Reference in New Issue
Block a user