From 09bb9d70ec669d22d338a70a6817c58221b07802 Mon Sep 17 00:00:00 2001 From: Wang Guan Date: Thu, 7 Sep 2023 00:30:28 +0900 Subject: [PATCH] useAsyncEffect: add preventDuplicatedRun --- src/react/hook/use-async-effect.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/react/hook/use-async-effect.ts b/src/react/hook/use-async-effect.ts index 2d19384..dccf83b 100644 --- a/src/react/hook/use-async-effect.ts +++ b/src/react/hook/use-async-effect.ts @@ -1,22 +1,32 @@ import { RefObject, useEffect, DependencyList } from 'react'; import { Deferred } from '../../concurrency/deferred'; +const nextTick = Promise.resolve(); + export function useAsyncEffect( effectCallback: ( running: RefObject, released: PromiseLike, ) => Promise, deps?: DependencyList, + preventDuplicatedRun = false, ): void { useEffect(() => { const mounted = { current: true }; const effectReleased = new Deferred(true); + const run = preventDuplicatedRun + ? async () => { + await nextTick; + if (!mounted.current) return; + return effectCallback(mounted, effectReleased); + } + : () => effectCallback(mounted, effectReleased); if (typeof setImmediate === 'function') { - setImmediate(() => effectCallback(mounted, effectReleased)); + setImmediate(run); } else { - setTimeout(() => effectCallback(mounted, effectReleased)); + setTimeout(run); } return () => {