Skip to content

Instantly share code, notes, and snippets.

@hasufell
Last active July 5, 2019 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasufell/16625fa2d32c5d7e0f9ba179e2b020a9 to your computer and use it in GitHub Desktop.
Save hasufell/16625fa2d32c5d7e0f9ba179e2b020a9 to your computer and use it in GitHub Desktop.
/**
* 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