From f09fce314076a7700abbe72dafeb907b6ff8e683 Mon Sep 17 00:00:00 2001 From: Pabloader Date: Mon, 20 Apr 2026 10:27:39 +0000 Subject: [PATCH] Async cleanup --- src/common/hooks/useAsyncEffect.ts | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) 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);