@@ -0,0 +1,59 @@
1+import { useCallback } from "react";
2+import { getErrorMessage, getParseErrorMessage, handleError } from "@/src/lib/errors";
3+
4+export interface FetchOptions extends RequestInit {
5+ errorMessage?: string;
6+ throwOnError?: boolean;
7+ onError?: (error: string) => void;
8+}
9+
10+/**
11+ * Custom hook that provides a reusable fetch function with standardized error handling.
12+ * Handles response validation, JSON parsing, and error callbacks.
13+ *
14+ * @returns A fetch function that handles errors automatically
15+ */
16+export function useFetch() {
17+ const fetchWithErrorHandling = useCallback(
18+ async <T = unknown>(url: string, options: FetchOptions = {}): Promise<T | null> => {
19+ const { errorMessage, throwOnError, onError, ...fetchOptions } = options;
20+
21+ try {
22+ const res = await fetch(url, fetchOptions);
23+ if (!res.ok) {
24+ const defaultError = errorMessage || `Failed to fetch: ${res.status}`;
25+ try {
26+ const errorData = await res.json();
27+ throw new Error(errorData.error || defaultError);
28+ } catch (parseError) {
29+ if (parseError instanceof Error && parseError.message !== defaultError) {
30+ throw parseError;
31+ }
32+ throw new Error(getParseErrorMessage(parseError));
33+ }
34+ }
35+ // Handle empty responses (e.g., 204 No Content)
36+ const contentType = res.headers.get("content-type");
37+ if (!contentType || !contentType.includes("application/json")) {
38+ return {} as T;
39+ }
40+ const text = await res.text();
41+ if (!text.trim()) {
42+ return {} as T;
43+ }
44+ const data = JSON.parse(text);
45+ return data as T;
46+ } catch (error) {
47+ const errorMsg = getErrorMessage(error, errorMessage || "Unknown error");
48+ handleError(errorMsg, onError);
49+ if (throwOnError) {
50+ throw error;
51+ }
52+ return null;
53+ }
54+ },
55+ []
56+ );
57+
58+ return fetchWithErrorHandling;
59+}