UNPKG

@kentcdodds/tmp-remix-utils

Version:

This package contains simple utility functions to use with [Remix.run](https://remix.run).

27 lines (26 loc) 844 B
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; }