import { useEffect } from "preact/hooks";

type Cleanup = void | (() => void);
type AsyncCleanup = Promise<Cleanup> | 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);
