import { useCallback, useRef } from "react"; import { useAlert } from "../context/AlertContext"; import apiFetch from "../utils/api"; interface ApiCallResult { data: T | null; ok: boolean; response: Response | null; } export default function useApiCall() { const alert = useAlert(); const abortRef = useRef(null); const call = useCallback( async ( url: string, options: RequestInit = {}, errorMsg = "Chyba při načítání dat", ): Promise> => { if (abortRef.current) abortRef.current.abort(); const controller = new AbortController(); abortRef.current = controller; try { const { signal: _, ...restOptions } = options; const response = await apiFetch(url, { ...restOptions, signal: controller.signal, }); const data = await response.json(); if (!response.ok || !data.success) { alert.error(data.error || errorMsg); return { data: null, ok: false, response }; } return { data: data.data as T, ok: true, response }; } catch (err: unknown) { if (err instanceof Error && err.name === "AbortError") { return { data: null, ok: false, response: null }; } alert.error(errorMsg); return { data: null, ok: false, response: null }; } }, [alert], ); return { call }; }