Last active
February 15, 2020 12:44
-
-
Save aadityataparia/5914ac4ac433614b5e31a782e4643edc to your computer and use it in GitHub Desktop.
Debouce async function in react, function returns promise that resolves only when debouced function is fired
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 { useCallback, useMemo } from 'react' | |
import { debounce } from 'lodash' | |
export const useAsyncDebounced = (callback, time) => { | |
const debounced = useMemo( | |
() => | |
debounce( | |
(res, rej, ...args) => | |
callback(...args) | |
.then(res) | |
.catch(rej), | |
time | |
), | |
[callback, time] | |
) | |
const debouncedCallback = useCallback( | |
(...args) => | |
new Promise((res, rej) => { | |
debounced(res, rej, ...args) | |
}), | |
[debounced] | |
) | |
return debouncedCallback | |
} | |
/* | |
Usage: | |
const deboucedAsync = useAsyncDebouncedCallback((v) => fetch('search?query=' + v), 300) | |
With async hooks: | |
const { result, isLoading } = useAsyncCallback(deboucedAsync, [...]) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment