Created
May 22, 2021 00:37
-
-
Save yyyyaaa/f0339e1a7cb2a725a2584d1c46732d99 to your computer and use it in GitHub Desktop.
use-async-debounce-cb.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { useGetLatest } from './use-get-latest'; | |
export function useAsyncDebounce(defaultFn, defaultWait = 0) { | |
const debounceRef = React.useRef({}); | |
const getDefaultFn = useGetLatest(defaultFn); | |
const getDefaultWait = useGetLatest(defaultWait); | |
return React.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] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment