Async cleanup
This commit is contained in:
parent
acf2527d7e
commit
f09fce3140
|
|
@ -1,4 +1,23 @@
|
||||||
import { useEffect } from "preact/hooks";
|
import { useEffect } from "preact/hooks";
|
||||||
|
|
||||||
export const useAsyncEffect = (fx: () => any, deps: any[]) =>
|
type Cleanup = void | (() => void);
|
||||||
useEffect(() => void fx(), deps);
|
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);
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue