refactor(frontend): extract shared fetch lifecycle into useFetchData base hook

Eliminates ~100 lines of duplicated code across useListData and usePolledData
by creating a composable base hook that handles:
- Abort controller lifecycle and cancellation
- Loading/error state management
- Fetch error handling
- Unmount cleanup

Changes:
- Create hooks/useFetchData.ts with base fetch lifecycle (no effects on consumers)
- Refactor useListData to compose useFetchData, returns items array by default
- Refactor usePolledData to compose useFetchData, adds polling and focus-refetch
- Add comprehensive tests for useFetchData base hook
- Document hook architecture and composition pattern in Web-Development.md

Result: Both hooks now use shared primitives, reducing maintenance burden
and ensuring consistent cancellation/error handling across all data fetches.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-28 09:23:34 +02:00
parent 5166789b68
commit d10145e5d6
6 changed files with 456 additions and 150 deletions

View File

@@ -0,0 +1,237 @@
import { describe, it, expect, vi } from "vitest";
import { renderHook, act } from "@testing-library/react";
import { useFetchData } from "../useFetchData";
import type { FetchError } from "../../types/api";
describe("useFetchData", () => {
it("fetches and selects data on mount", async () => {
const fetcher = vi.fn().mockResolvedValue({ value: "test" });
const selector = vi.fn((response: { value: string }) => response.value);
const { result } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed to load",
})
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBeUndefined();
await act(async () => {
await Promise.resolve();
});
expect(fetcher).toHaveBeenCalledTimes(1);
expect(selector).toHaveBeenCalledWith({ value: "test" });
expect(result.current.data).toBe("test");
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeNull();
});
it("uses initial data if provided", () => {
const fetcher = vi.fn().mockResolvedValue({ value: "updated" });
const selector = vi.fn();
const { result } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed to load",
initialData: "initial",
})
);
expect(result.current.data).toBe("initial");
expect(result.current.loading).toBe(true);
});
it("sets typed error when fetcher rejects", async () => {
const fetcher = vi.fn().mockRejectedValue(new Error("network error"));
const selector = vi.fn();
const { result } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed to load",
})
);
await act(async () => {
await Promise.resolve();
});
const error = result.current.error as FetchError | null;
expect(error).not.toBeNull();
expect(error?.type).toBe("network_error");
expect(result.current.loading).toBe(false);
expect(result.current.data).toBeUndefined();
});
it("calls onSuccess callback after successful fetch", async () => {
const response = { value: "success" };
const fetcher = vi.fn().mockResolvedValue(response);
const selector = vi.fn((r: typeof response) => r.value);
const onSuccess = vi.fn();
const { result } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed",
onSuccess,
})
);
await act(async () => {
await Promise.resolve();
});
expect(onSuccess).toHaveBeenCalledWith(response);
expect(result.current.data).toBe("success");
});
it("refresh triggers a new fetch", async () => {
const fetcher = vi
.fn()
.mockResolvedValueOnce({ value: "first" })
.mockResolvedValueOnce({ value: "second" });
const selector = vi.fn((response: { value: string }) => response.value);
const { result } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed to load",
})
);
await act(async () => {
await Promise.resolve();
});
expect(result.current.data).toBe("first");
await act(async () => {
result.current.refresh();
await Promise.resolve();
});
expect(fetcher).toHaveBeenCalledTimes(2);
expect(result.current.data).toBe("second");
});
it("aborts previous request when refresh is called", async () => {
const abortedSignals: AbortSignal[] = [];
const fetcher = vi.fn().mockImplementation(async (signal: AbortSignal) => {
abortedSignals.push(signal);
await new Promise((resolve) => setTimeout(resolve, 50));
return { value: "done" };
});
const selector = vi.fn();
const { result } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed to load",
})
);
await act(async () => {
await Promise.resolve();
});
// Trigger refresh
await act(async () => {
result.current.refresh();
await Promise.resolve();
});
// First signal should have been aborted
expect(abortedSignals[0]?.aborted).toBe(true);
});
it("does not update state when signal is aborted", async () => {
const fetcher = vi.fn().mockImplementation(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
return { value: "late" };
});
const selector = vi.fn((response: { value: string }) => response.value);
const { result, unmount } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed to load",
})
);
// Unmount immediately
await act(async () => {
await Promise.resolve();
});
unmount();
// Data should not be updated
expect(result.current.data).toBeUndefined();
expect(result.current.loading).toBe(true); // frozen at true due to abort
});
it("silently handles abort errors", async () => {
const fetcher = vi
.fn()
.mockRejectedValue(new DOMException("Aborted", "AbortError"));
const selector = vi.fn();
const { result } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed to load",
})
);
await act(async () => {
await Promise.resolve();
});
// Abort errors should not set error state
expect(result.current.error).toBeNull();
});
it("exposes typed API error information", async () => {
const fetcher = vi.fn().mockImplementation(() => {
return Promise.reject((() => {
const error = new Error("API error 500: Server error");
(error as any).name = "ApiError";
(error as any).status = 500;
(error as any).body = "Server error";
return error;
})());
});
const selector = vi.fn();
const { result } = renderHook(() =>
useFetchData({
fetcher,
selector,
errorMessage: "Failed to load",
})
);
await act(async () => {
await Promise.resolve();
});
const error = result.current.error as FetchError | null;
expect(error).not.toBeNull();
expect(error?.type).toBe("api_error");
if (error?.type === "api_error") {
expect(error.status).toBe(500);
expect(error.body).toBe("Server error");
}
});
});

View File

@@ -0,0 +1,97 @@
/**
* Composable base hook for fetch lifecycle, cancellation, and error handling.
*
* Provides common primitives for data-fetching hooks: abort controller management,
* loading/error state, and a refresh callback with cancellation safety.
*
* This is an internal hook meant to be composed by higher-level hooks like
* useListData and usePolledData. Direct usage is discouraged — instead,
* create a domain-specific hook that wraps this base and adds your specific
* requirements (e.g., polling, windowed effects, derived state).
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { handleFetchError } from "../utils/fetchError";
import type { FetchError } from "../types/api";
export interface UseFetchDataOptions<TResponse, TData> {
/** Async function that accepts an AbortSignal for cancellation. */
fetcher: (signal: AbortSignal) => Promise<TResponse>;
/** Synchronous selector to extract domain data from the response. */
selector: (response: TResponse) => TData;
/** Human-readable error message used as fallback if fetch fails. */
errorMessage: string;
/** Optional callback invoked after successful fetch with full response. */
onSuccess?: (response: TResponse) => void;
/** Initial data value. If undefined, data starts as undefined until first fetch. */
initialData?: TData;
}
export interface UseFetchDataResult<TData> {
/** The extracted data from the most recent successful fetch. */
data: TData | undefined;
/** True while a fetch is in-flight, false when complete. */
loading: boolean;
/** Typed error or null. Check `error?.type` to handle specific failure modes. */
error: FetchError | null;
/** Trigger a fresh fetch. Cancels any in-flight request first. */
refresh: () => void;
}
/**
* Generic base hook that manages the fetch lifecycle for a single resource.
*
* Handles abort controller management, error handling, and refresh semantics.
* Automatically cancels in-flight requests on component unmount.
*
* Prefer composing this hook via higher-level hooks (useListData, usePolledData)
* rather than using directly.
*
* @param options - Configuration: fetcher, selector, error message, and optional callbacks
* @returns Data, loading state, typed error, and refresh callback
*/
export function useFetchData<TResponse, TData>(
options: UseFetchDataOptions<TResponse, TData>,
): UseFetchDataResult<TData> {
const { fetcher, selector, errorMessage, onSuccess, initialData } = options;
const [data, setData] = useState<TData | undefined>(initialData);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<FetchError | null>(null);
const abortRef = useRef<AbortController | null>(null);
const refresh = useCallback((): void => {
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setLoading(true);
setError(null);
fetcher(controller.signal)
.then((response) => {
if (controller.signal.aborted) return;
setData(selector(response));
if (onSuccess) {
onSuccess(response);
}
})
.catch((err: unknown) => {
if (controller.signal.aborted) return;
handleFetchError(err, setError, errorMessage);
})
.finally(() => {
if (!controller.signal.aborted) {
setLoading(false);
}
});
}, [fetcher, selector, errorMessage, onSuccess]);
useEffect(() => {
refresh();
return (): void => {
abortRef.current?.abort();
};
}, [refresh]);
return { data, loading, error, refresh };
}

View File

@@ -1,22 +1,33 @@
/**
* Generic hook for loading list data from an API endpoint.
*
* Composes useFetchData to provide a list-specific interface where initial
* data defaults to an empty array and the result is typed as `items: TItem[]`.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { handleFetchError } from "../utils/fetchError";
import { useFetchData } from "./useFetchData";
import type { FetchError } from "../types/api";
export interface UseListDataOptions<TResponse, TItem> {
/** Async function that accepts an AbortSignal for cancellation. */
fetcher: (signal: AbortSignal) => Promise<TResponse>;
/** Synchronous selector to extract items array from response. */
selector: (response: TResponse) => TItem[];
/** Human-readable error message used as fallback if fetch fails. */
errorMessage: string;
/** Optional callback invoked after successful fetch with full response. */
onSuccess?: (response: TResponse) => void;
/** Initial items array. Defaults to empty array. */
initialItems?: TItem[];
}
export interface UseListDataResult<TItem> {
/** The extracted items array from the most recent successful fetch. */
items: TItem[];
/** True while a fetch is in-flight, false when complete. */
loading: boolean;
/** Typed error or null. Check `error?.type` to handle specific failure modes. */
error: FetchError | null;
/** Trigger a fresh fetch. Cancels any in-flight request first. */
refresh: () => void;
}
@@ -32,51 +43,20 @@ export interface UseListDataResult<TItem> {
* - `"abort_error"`: Request was cancelled (typically silently ignored by hook)
*
* @param options - Configuration options
* @returns Data, loading state, typed error, and refresh callback
* @returns List data, loading state, typed error, and refresh callback
*/
export function useListData<TResponse, TItem>(
options: UseListDataOptions<TResponse, TItem>,
): UseListDataResult<TItem> {
const { fetcher, selector, errorMessage, onSuccess, initialItems } = options;
const [items, setItems] = useState<TItem[]>(initialItems ?? []);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<FetchError | null>(null);
const abortRef = useRef<AbortController | null>(null);
const refresh = useCallback((): void => {
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
const { data, loading, error, refresh } = useFetchData({
fetcher,
selector,
errorMessage,
onSuccess,
initialData: initialItems ?? [],
});
setLoading(true);
setError(null);
fetcher(controller.signal)
.then((response) => {
if (controller.signal.aborted) return;
setItems(selector(response));
if (onSuccess) {
onSuccess(response);
}
})
.catch((err: unknown) => {
if (controller.signal.aborted) return;
handleFetchError(err, setError, errorMessage);
})
.finally(() => {
if (!controller.signal.aborted) {
setLoading(false);
}
});
}, [fetcher, selector, errorMessage, onSuccess]);
useEffect(() => {
refresh();
return (): void => {
abortRef.current?.abort();
};
}, [refresh]);
return { items, loading, error, refresh };
return { items: data ?? [], loading, error, refresh };
}

View File

@@ -1,27 +1,38 @@
/**
* Generic hook for loading and polling single-item data from an API endpoint.
*
* Similar to useListData, but for non-list endpoints that need periodic polling
* and window-focus refetch semantics.
* Composes useFetchData and adds polling and window-focus refetch semantics
* for non-list endpoints that need periodic updates.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { handleFetchError } from "../utils/fetchError";
import { useEffect, useRef } from "react";
import { useFetchData } from "./useFetchData";
import type { FetchError } from "../types/api";
export interface UsePolledDataOptions<TResponse, TData> {
/** Async function that accepts an AbortSignal for cancellation. */
fetcher: (signal: AbortSignal) => Promise<TResponse>;
/** Synchronous selector to extract data from response. */
selector: (response: TResponse) => TData;
/** Human-readable error message used as fallback if fetch fails. */
errorMessage: string;
/** Optional callback invoked after successful fetch with full response. */
onSuccess?: (response: TResponse) => void;
/** Initial data value. Defaults to null. */
initialData?: TData;
/** Polling interval in milliseconds. If unset, no periodic polling. */
pollInterval?: number;
/** If true, automatically refetch when browser window regains focus. Defaults to true. */
refetchOnWindowFocus?: boolean;
}
export interface UsePolledDataResult<TData> {
/** The extracted data from the most recent successful fetch, or null if not yet fetched. */
data: TData | null;
/** True while a fetch is in-flight, false when complete. */
loading: boolean;
/** Typed error or null. Check `error?.type` to handle specific failure modes. */
error: FetchError | null;
/** Trigger a fresh fetch. Cancels any in-flight request first. */
refresh: () => void;
}
@@ -52,66 +63,41 @@ export function usePolledData<TResponse, TData>(
refetchOnWindowFocus = true,
} = options;
const [data, setData] = useState<TData | null>(initialData ?? null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<FetchError | null>(null);
const abortRef = useRef<AbortController | null>(null);
const fetchRef = useRef<() => void>((): void => undefined);
const { data, loading, error, refresh } = useFetchData({
fetcher,
selector,
errorMessage,
onSuccess,
initialData,
});
const refresh = useCallback((): void => {
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setLoading(true);
setError(null);
fetcher(controller.signal)
.then((response) => {
if (controller.signal.aborted) return;
setData(selector(response));
if (onSuccess) {
onSuccess(response);
}
})
.catch((err: unknown) => {
if (controller.signal.aborted) return;
handleFetchError(err, setError, errorMessage);
})
.finally(() => {
if (!controller.signal.aborted) {
setLoading(false);
}
});
}, [fetcher, selector, errorMessage, onSuccess]);
fetchRef.current = refresh;
const refreshRef = useRef(refresh);
useEffect(() => {
refresh();
refreshRef.current = refresh;
}, [refresh]);
// Polling effect: set up interval if pollInterval is provided
useEffect(() => {
if (!pollInterval) {
return (): void => {
abortRef.current?.abort();
};
return;
}
const id = setInterval((): void => {
fetchRef.current();
refreshRef.current();
}, pollInterval);
return (): void => {
clearInterval(id);
abortRef.current?.abort();
};
}, [refresh, pollInterval]);
}, [pollInterval]);
// Refetch on window focus if enabled.
// Window focus: optional refetch on regain focus
useEffect(() => {
if (!refetchOnWindowFocus) return;
const onFocus = (): void => {
fetchRef.current();
refreshRef.current();
};
window.addEventListener("focus", onFocus);
@@ -120,5 +106,5 @@ export function usePolledData<TResponse, TData>(
};
}, [refetchOnWindowFocus]);
return { data, loading, error, refresh };
return { data: data ?? null, loading, error, refresh };
}