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