Skip to content

Instantly share code, notes, and snippets.

@arabold
Last active February 15, 2022 19:00
Show Gist options
  • Save arabold/e7e5d64d2d28a94ef78fe383e6a70c1c to your computer and use it in GitHub Desktop.
Save arabold/e7e5d64d2d28a94ef78fe383e6a70c1c to your computer and use it in GitHub Desktop.
/**
* Wrap async handler functions for use with `onPress` and similar React callbacks, which are typically
* not safe to use with promises. `useAsyncFunc` gracefully handles any promise errors.
*
* Note that this hook, unlike `useCallback`, does not memoize the callback function itself. To create
* a memoized function wrap it with `useCallback` instead.
* @example
* ```tsx
* const handlePress = useAsyncFunc(async () => {
* await doSomething();
* });
*
* return <Button onPress={handlePress} ... />;
* ```
*/
export default function useAsyncFunc<ArgsT extends any[], ReturnT>(
func: (...args: ArgsT) => Promise<ReturnT> | ReturnT,
errorFunc?: (error: any) => Promise<void> | void,
): (...args: ArgsT) => void {
return (...args: ArgsT): void => {
Promise.resolve()
.then(() => func(...args))
.catch((error) => {
if (typeof errorFunc === "function") {
return errorFunc(error);
} else {
console.log(error);
}
})
.catch(null); // no particular error handling for the error handling itself
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment