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:
@@ -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 };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user