Created
September 23, 2024 15:42
-
-
Save Phryxia/049affe0234e0b8b1c100f44819934b3 to your computer and use it in GitHub Desktop.
Convenient useAsyncEffect for react.js
This file contains hidden or 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 { useEffect } from 'react'; | |
type UseAsyncEffectCleaner = () => Promise<void> | void; | |
type UseAsyncEffectCallback = () => | |
| Promise<UseAsyncEffectCleaner | void> | |
| UseAsyncEffectCleaner | |
| void; | |
export function useAsyncEffect(fn: UseAsyncEffectCallback, deps?: any[]) { | |
return useEffect(() => { | |
const ret = fn(); | |
if (!ret) return; | |
if (typeof ret === 'function') { | |
return () => void ret(); | |
} | |
return () => void ret.then((cleaner) => cleaner?.()); | |
}, deps); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment