52 lines
1.8 KiB
TypeScript
52 lines
1.8 KiB
TypeScript
import { useEffect, useLayoutEffect, useRef } from "react";
|
|
import { makeRequest } from "../api";
|
|
import { Tariff, GetTariffsResponse } from "../model/tariff";
|
|
import { devlog } from "../utils";
|
|
import { FetchState } from "../model/fetchState";
|
|
|
|
|
|
export function usePaginatedTariffsFetcher({ enabled = true, url, tariffsPerPage, apiPage, onSuccess, onError, onFetchStateChange }: {
|
|
enabled?: boolean;
|
|
url: string;
|
|
tariffsPerPage: number;
|
|
apiPage: number;
|
|
onSuccess: (response: Tariff[]) => void;
|
|
onError?: (error: Error) => void;
|
|
onFetchStateChange?: (state: FetchState) => void;
|
|
}) {
|
|
const onNewTariffsRef = useRef(onSuccess);
|
|
const onErrorRef = useRef(onError);
|
|
const onFetchStateChangeRef = useRef(onFetchStateChange);
|
|
|
|
useLayoutEffect(() => {
|
|
onNewTariffsRef.current = onSuccess;
|
|
onErrorRef.current = onError;
|
|
onFetchStateChangeRef.current = onFetchStateChange;
|
|
}, [onSuccess, onError, onFetchStateChange]);
|
|
|
|
useEffect(function fetchTickets() {
|
|
if (!enabled) return;
|
|
|
|
const controller = new AbortController();
|
|
|
|
onFetchStateChangeRef.current?.("fetching");
|
|
makeRequest<never, GetTariffsResponse>({
|
|
url,
|
|
method: "get",
|
|
useToken: true,
|
|
signal: controller.signal,
|
|
}).then((result) => {
|
|
devlog("GetTariffsResponse", result);
|
|
if (result.tariffs.length > 0) {
|
|
onNewTariffsRef.current(result.tariffs);
|
|
onFetchStateChangeRef.current?.("idle");
|
|
} else onFetchStateChangeRef.current?.("all fetched");
|
|
}).catch(error => {
|
|
devlog("Error fetching tariffs", error);
|
|
onErrorRef.current?.(error);
|
|
});
|
|
|
|
return () => controller.abort();
|
|
}, [apiPage, enabled, tariffsPerPage, url]);
|
|
}
|