diff --git a/src/common/hooks/useAsyncEffect.ts b/src/common/hooks/useAsyncEffect.ts index ef80bc5..0a10258 100644 --- a/src/common/hooks/useAsyncEffect.ts +++ b/src/common/hooks/useAsyncEffect.ts @@ -1,4 +1,23 @@ import { useEffect } from "preact/hooks"; -export const useAsyncEffect = (fx: () => any, deps: any[]) => - useEffect(() => void fx(), deps); +type Cleanup = void | (() => void); +type AsyncCleanup = Promise | Cleanup; + +export const useAsyncEffect = (fx: () => AsyncCleanup, deps: any[]) => + useEffect(() => { + let cleanup: Cleanup; + let cancelled = false; + + Promise.resolve(fx()).then((result) => { + if (cancelled) { + result?.(); + } else { + cleanup = result; + } + }); + + return () => { + cancelled = true; + cleanup?.(); + }; + }, deps);