2023-11-05 23:33:40 +00:00
|
|
|
import { useEffect, useLayoutEffect, useRef, useState } from "react"
|
2023-08-08 12:59:23 +00:00
|
|
|
|
2023-11-05 23:33:40 +00:00
|
|
|
import { getTariffs } from "@root/api/tariff"
|
2023-08-31 10:02:11 +00:00
|
|
|
|
2023-11-05 23:33:40 +00:00
|
|
|
import type { Tariff } from "@frontend/kitui"
|
2023-08-08 12:59:23 +00:00
|
|
|
|
|
|
|
export function useTariffFetcher({
|
2023-11-05 23:33:40 +00:00
|
|
|
tariffsPerPage,
|
|
|
|
apiPage,
|
|
|
|
onSuccess,
|
|
|
|
onError,
|
2023-08-08 12:59:23 +00:00
|
|
|
}: {
|
2023-08-31 10:02:11 +00:00
|
|
|
baseUrl?: string;
|
|
|
|
tariffsPerPage: number;
|
|
|
|
apiPage: number;
|
|
|
|
onSuccess: (response: Tariff[]) => void;
|
|
|
|
onError?: (error: Error) => void;
|
2023-08-08 12:59:23 +00:00
|
|
|
}) {
|
2023-11-05 23:33:40 +00:00
|
|
|
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")
|
|
|
|
getTariffs(apiPage, tariffsPerPage, controller.signal)
|
|
|
|
.then(([result]) => {
|
|
|
|
if (result && result.tariffs.length > 0) {
|
|
|
|
onSuccessRef.current(result.tariffs)
|
|
|
|
setFetchState("idle")
|
|
|
|
} else setFetchState("all fetched")
|
|
|
|
})
|
|
|
|
.catch(([_, error]) => {
|
|
|
|
onErrorRef.current?.(error)
|
|
|
|
})
|
|
|
|
|
|
|
|
return () => controller.abort()
|
|
|
|
}, [apiPage, tariffsPerPage])
|
|
|
|
|
|
|
|
return fetchState
|
2023-08-08 12:59:23 +00:00
|
|
|
}
|