Skip to content

Instantly share code, notes, and snippets.

@hasufell hasufell/debounce.ts
Last active Jul 5, 2019

Embed
What would you like to do?
/**
* Returns a constant value. This will only
* be computed on the first render.
*/
export function useConst<T>(value: T | (() => T)): T {
const [state] = useState<T>(() =>
typeof value === "function" ? (value as Function)() : value
);
return state;
}
/**
* Debounce an async function with the given timer.
* The return value will be the current state of
* running the function. Look at it as a delayed value.
*
* @param fn the function to debounce, must be created with useConst
* @param params the parameter to the constant function, these may change
* @param initvalue the initial value
* @param timeout the timeout for the debouncer
*/
export function useDebounce<T, Args extends any[]>(
fn: (...args: Args) => Promise<T>,
params: Args,
initvalue: T | (() => T),
timeout: number
): T {
const [state, setState] = useState<T>(initvalue);
const debounced = useConst(() => AwesomeDebouncePromise(fn, timeout));
const res = useAsync(debounced, params);
useEffect(() => {
if (res.result) {
setState(res.result);
}
}, [res.result]);
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.