Skip to content

Instantly share code, notes, and snippets.

@rmdort
Created April 14, 2023 17:38
Show Gist options
  • Save rmdort/64fe683c5efe0576d5a8ee9c5398da3f to your computer and use it in GitHub Desktop.
Save rmdort/64fe683c5efe0576d5a8ee9c5398da3f to your computer and use it in GitHub Desktop.
import { useCallback, useRef, useSyncExternalStore } from "react";
export const useAsyncHook = <T>(fn: () => Promise<T> | undefined) => {
const resultRef = useRef<T>();
const getSnapShot = () => resultRef.current;
const subscribe = useCallback(
(onStoreChange: () => void) => {
const executeAsync = async () => {
try {
const result = await fn?.();
resultRef.current = result;
} catch (err) {
resultRef.current = undefined;
}
onStoreChange();
};
executeAsync();
return () => undefined;
},
[fn]
);
return useSyncExternalStore(subscribe, getSnapShot, getSnapShot);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment