Last active
July 5, 2019 15:20
-
-
Save hasufell/16625fa2d32c5d7e0f9ba179e2b020a9 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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