UNPKG

@airplane/views

Version:

A React library for building Airplane views. Views components are optimized in style and functionality to produce internal apps that are easy to build and maintain.

38 lines (37 loc) 1.21 kB
import { useRef, useCallback } from "react"; function useGetLatest(obj) { const ref = useRef(); ref.current = obj; return useCallback(() => ref.current, []); } function useAsyncDebounce(defaultFn, defaultWait = 0) { const debounceRef = useRef({}); const getDefaultFn = useGetLatest(defaultFn); const getDefaultWait = useGetLatest(defaultWait); return useCallback(async (...args) => { if (!debounceRef.current.promise) { debounceRef.current.promise = new Promise((resolve, reject) => { debounceRef.current.resolve = resolve; debounceRef.current.reject = reject; }); } if (debounceRef.current.timeout) { clearTimeout(debounceRef.current.timeout); } debounceRef.current.timeout = setTimeout(async () => { delete debounceRef.current.timeout; try { debounceRef.current.resolve(await getDefaultFn()(...args)); } catch (err) { debounceRef.current.reject(err); } finally { delete debounceRef.current.promise; } }, getDefaultWait()); return debounceRef.current.promise; }, [getDefaultFn, getDefaultWait]); } export { useAsyncDebounce }; //# sourceMappingURL=useAsyncDebounce.js.map