Created
April 14, 2023 17:38
-
-
Save rmdort/64fe683c5efe0576d5a8ee9c5398da3f 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
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