2023-08-29 11:16:10 +00:00
|
|
|
import { useEffect, useRef, useLayoutEffect } from "react";
|
2023-06-06 10:02:17 +00:00
|
|
|
import { GetTicketsResponse, GetTicketsRequest } from "../model";
|
|
|
|
import { devlog } from "../utils";
|
2023-06-11 09:55:06 +00:00
|
|
|
import { makeRequest } from "../api";
|
2023-08-29 11:16:10 +00:00
|
|
|
import { FetchState } from "../model/fetchState";
|
2023-06-06 10:02:17 +00:00
|
|
|
|
|
|
|
|
2023-08-29 13:24:51 +00:00
|
|
|
export function useTicketsFetcher({ enabled = true, url, ticketsPerPage, ticketApiPage, onSuccess, onError, onFetchStateChange }: {
|
|
|
|
enabled?: boolean;
|
2023-06-06 10:02:17 +00:00
|
|
|
url: string;
|
|
|
|
ticketsPerPage: number;
|
|
|
|
ticketApiPage: number;
|
2023-08-29 11:16:10 +00:00
|
|
|
onSuccess: (response: GetTicketsResponse) => 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-06 10:02:17 +00:00
|
|
|
}) {
|
2023-08-29 11:16:10 +00:00
|
|
|
const onNewTicketsRef = 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
|
|
|
onNewTicketsRef.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-06 10:02:17 +00:00
|
|
|
|
|
|
|
useEffect(function fetchTickets() {
|
2023-08-29 13:24:51 +00:00
|
|
|
if (!enabled) return;
|
|
|
|
|
2023-06-06 10:02:17 +00:00
|
|
|
const controller = new AbortController();
|
|
|
|
|
2023-08-29 11:16:10 +00:00
|
|
|
onFetchStateChangeRef.current?.("fetching");
|
2023-06-06 10:02:17 +00:00
|
|
|
makeRequest<GetTicketsRequest, GetTicketsResponse>({
|
|
|
|
url,
|
|
|
|
method: "POST",
|
|
|
|
useToken: true,
|
|
|
|
body: {
|
|
|
|
amt: ticketsPerPage,
|
|
|
|
page: ticketApiPage,
|
|
|
|
status: "open",
|
|
|
|
},
|
|
|
|
signal: controller.signal,
|
|
|
|
}).then((result) => {
|
|
|
|
devlog("GetTicketsResponse", result);
|
|
|
|
if (result.data) {
|
2023-07-10 17:48:09 +00:00
|
|
|
onNewTicketsRef.current(result);
|
2023-08-29 11:16:10 +00:00
|
|
|
onFetchStateChangeRef.current?.("idle");
|
|
|
|
} else onFetchStateChangeRef.current?.("all fetched");
|
2023-06-06 10:02:17 +00:00
|
|
|
}).catch(error => {
|
2023-06-17 14:27:22 +00:00
|
|
|
devlog("Error fetching tickets", error);
|
2023-08-28 14:30:43 +00:00
|
|
|
onErrorRef.current?.(error);
|
2023-06-06 10:02:17 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return () => controller.abort();
|
2023-08-29 13:24:51 +00:00
|
|
|
}, [enabled, ticketApiPage, ticketsPerPage, url]);
|
2023-08-28 14:30:43 +00:00
|
|
|
}
|