39 lines
1.3 KiB
TypeScript
39 lines
1.3 KiB
TypeScript
![]() |
import { useEffect, useState } from "react";
|
||
|
import { makeRequest } from "../api";
|
||
|
import { Tariff, GetTariffsResponse } from "../model/tariff";
|
||
|
|
||
|
|
||
|
export function useTariffs({ url, tariffsPerPage, apiPage, onNewTariffs, onError }: {
|
||
|
url: string;
|
||
|
tariffsPerPage: number;
|
||
|
apiPage: number;
|
||
|
onNewTariffs: (response: Tariff[]) => void;
|
||
|
onError: (error: Error) => void;
|
||
|
}) {
|
||
|
const [fetchState, setFetchState] = useState<"fetching" | "idle" | "all fetched">("idle");
|
||
|
|
||
|
useEffect(function fetchTickets() {
|
||
|
const controller = new AbortController();
|
||
|
|
||
|
setFetchState("fetching");
|
||
|
makeRequest<never, GetTariffsResponse>({
|
||
|
url,
|
||
|
method: "get",
|
||
|
useToken: true,
|
||
|
signal: controller.signal,
|
||
|
}).then((result) => {
|
||
|
// devlog("GetTicketsResponse", result);
|
||
|
if (result.tariffs.length > 0) {
|
||
|
onNewTariffs(result.tariffs);
|
||
|
setFetchState("idle");
|
||
|
} else setFetchState("all fetched");
|
||
|
}).catch(error => {
|
||
|
console.log("Error fetching tariffs", error);
|
||
|
onError(error);
|
||
|
});
|
||
|
|
||
|
return () => controller.abort();
|
||
|
}, [onError, onNewTariffs, apiPage, tariffsPerPage, url]);
|
||
|
|
||
|
return fetchState;
|
||
|
}
|