Skip to content

Instantly share code, notes, and snippets.

@aadityataparia
Last active February 15, 2020 12:44
Show Gist options
  • Save aadityataparia/5914ac4ac433614b5e31a782e4643edc to your computer and use it in GitHub Desktop.
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
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