Skip to content

Instantly share code, notes, and snippets.

@yyyyaaa
Created May 22, 2021 00:37
Show Gist options
  • Save yyyyaaa/f0339e1a7cb2a725a2584d1c46732d99 to your computer and use it in GitHub Desktop.
Save yyyyaaa/f0339e1a7cb2a725a2584d1c46732d99 to your computer and use it in GitHub Desktop.
use-async-debounce-cb.js
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