UIKit/lib/hooks/usePaginatedTariffsFetcher.ts

52 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-08-29 11:16:10 +00:00
import { useEffect, useLayoutEffect, useRef } from "react";
2023-06-17 14:24:12 +00:00
import { makeRequest } from "../api";
import { Tariff, GetTariffsResponse } from "../model/tariff";
2023-06-17 14:27:22 +00:00
import { devlog } from "../utils";
2023-08-29 11:16:10 +00:00
import { FetchState } from "../model/fetchState";
2023-06-17 14:24:12 +00:00
2023-08-29 13:24:51 +00:00
export function usePaginatedTariffsFetcher({ enabled = true, url, tariffsPerPage, apiPage, onSuccess, onError, onFetchStateChange }: {
enabled?: boolean;
2023-06-17 14:24:12 +00:00
url: string;
tariffsPerPage: number;
apiPage: number;
2023-08-29 11:16:10 +00:00
onSuccess: (response: Tariff[]) => void;
2023-08-28 14:30:43 +00:00
onError?: (error: Error) => void;
2023-08-29 11:16:10 +00:00
onFetchStateChange?: (state: FetchState) => void;
2023-06-17 14:24:12 +00:00
}) {
2023-08-29 11:16:10 +00:00
const onNewTariffsRef = useRef(onSuccess);
2023-07-10 17:48:09 +00:00
const onErrorRef = useRef(onError);
2023-08-29 11:16:10 +00:00
const onFetchStateChangeRef = useRef(onFetchStateChange);
2023-07-10 17:48:09 +00:00
useLayoutEffect(() => {
2023-08-29 11:16:10 +00:00
onNewTariffsRef.current = onSuccess;
2023-07-10 17:48:09 +00:00
onErrorRef.current = onError;
2023-08-29 11:16:10 +00:00
onFetchStateChangeRef.current = onFetchStateChange;
}, [onSuccess, onError, onFetchStateChange]);
2023-06-17 14:24:12 +00:00
useEffect(function fetchTickets() {
2023-08-29 13:24:51 +00:00
if (!enabled) return;
2023-06-17 14:24:12 +00:00
const controller = new AbortController();
2023-08-29 11:16:10 +00:00
onFetchStateChangeRef.current?.("fetching");
2023-06-17 14:24:12 +00:00
makeRequest<never, GetTariffsResponse>({
url,
method: "get",
useToken: true,
signal: controller.signal,
}).then((result) => {
2023-06-17 14:27:22 +00:00
devlog("GetTariffsResponse", result);
2023-06-17 14:24:12 +00:00
if (result.tariffs.length > 0) {
2023-07-10 17:48:09 +00:00
onNewTariffsRef.current(result.tariffs);
2023-08-29 11:16:10 +00:00
onFetchStateChangeRef.current?.("idle");
} else onFetchStateChangeRef.current?.("all fetched");
2023-06-17 14:24:12 +00:00
}).catch(error => {
2023-06-17 14:27:22 +00:00
devlog("Error fetching tariffs", error);
2023-08-28 14:30:43 +00:00
onErrorRef.current?.(error);
2023-06-17 14:24:12 +00:00
});
return () => controller.abort();
2023-08-29 13:24:51 +00:00
}, [apiPage, enabled, tariffsPerPage, url]);
2023-08-28 14:30:43 +00:00
}