import { Tariff, makeRequest } from "@frontend/kitui"; import { GetTariffsResponse } from "@root/model/tariff"; import { useEffect, useLayoutEffect, useRef, useState } from "react"; export function useTariffFetcher({ baseUrl = process.env.NODE_ENV === "production" ? "/strator/tariff" : "https://hub.pena.digital/strator/tariff", tariffsPerPage, apiPage, onSuccess, onError, }: { baseUrl?: string; tariffsPerPage: number; apiPage: number; onSuccess: (response: Tariff[]) => void; onError?: (error: Error) => void; }) { const [fetchState, setFetchState] = useState<"fetching" | "idle" | "all fetched">("idle"); const onSuccessRef = useRef(onSuccess); const onErrorRef = useRef(onError); useLayoutEffect(() => { onSuccessRef.current = onSuccess; onErrorRef.current = onError; }, [onError, onSuccess]); useEffect(() => { const controller = new AbortController(); setFetchState("fetching"); makeRequest({ url: baseUrl + `?page=${apiPage}&limit=${tariffsPerPage}`, method: "get", useToken: true, signal: controller.signal, }).then((result) => { if (result.tariffs.length > 0) { onSuccessRef.current(result.tariffs); setFetchState("idle"); } else setFetchState("all fetched"); }).catch(error => { onErrorRef.current?.(error); }); return () => controller.abort(); }, [apiPage, tariffsPerPage, baseUrl]); return fetchState; }