import { useFetcher } from "@remix-run/react";
import { useCallback, useEffect, useRef } from "react";
export function useDebounceFetcher() {
  let timeoutRef = useRef();
  useEffect(() => {
    // no initialize step required since timeoutRef defaults undefined
    let timeout = timeoutRef.current;
    return () => {
      if (timeout) clearTimeout(timeout);
    };
  }, [timeoutRef]);
  let fetcher = useFetcher();
  fetcher.submit = useCallback(
    (target, { debounceTimeout = 0, ...options } = {}) => {
      if (timeoutRef.current) clearTimeout(timeoutRef.current);
      if (!debounceTimeout || debounceTimeout <= 0) {
        return fetcher.submit(target, options);
      }
      timeoutRef.current = setTimeout(() => {
        fetcher.submit(target, options);
      }, debounceTimeout);
    },
    [fetcher]
  );
  return fetcher;
}
