import { useEffect, useRef, useLayoutEffect } from "react"; import { GetTicketsResponse, GetTicketsRequest } from "../model"; import { devlog } from "../utils"; import { makeRequest } from "../api"; import { FetchState } from "../model/fetchState"; export function useTicketsFetcher({ enabled = true, url, ticketsPerPage, ticketApiPage, onSuccess, onError, onFetchStateChange }: { enabled?: boolean; url: string; ticketsPerPage: number; ticketApiPage: number; onSuccess: (response: GetTicketsResponse) => void; onError?: (error: Error) => void; onFetchStateChange?: (state: FetchState) => void; }) { const onNewTicketsRef = useRef(onSuccess); const onErrorRef = useRef(onError); const onFetchStateChangeRef = useRef(onFetchStateChange); useLayoutEffect(() => { onNewTicketsRef.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({ url, method: "POST", useToken: true, body: { amt: ticketsPerPage, page: ticketApiPage, status: "open", }, signal: controller.signal, }).then((result) => { devlog("GetTicketsResponse", result); if (result.data) { onNewTicketsRef.current(result); onFetchStateChangeRef.current?.("idle"); } else onFetchStateChangeRef.current?.("all fetched"); }).catch(error => { devlog("Error fetching tickets", error); onErrorRef.current?.(error); }); return () => controller.abort(); }, [enabled, ticketApiPage, ticketsPerPage, url]); }