Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useAsyncEffect: add preventDuplicatedRun #50

Merged
merged 1 commit into from
Sep 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/react/hook/use-async-effect.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,32 @@
import { RefObject, useEffect, DependencyList } from 'react';
import { Deferred } from '../../concurrency/deferred';

const nextTick = Promise.resolve();

Check warning on line 4 in src/react/hook/use-async-effect.ts

View check run for this annotation

Codecov / codecov/patch

src/react/hook/use-async-effect.ts#L4

Added line #L4 was not covered by tests

export function useAsyncEffect(
effectCallback: (
running: RefObject<boolean>,
released: PromiseLike<void>,
) => Promise</* cleanup should be done with released */ void>,
deps?: DependencyList,
preventDuplicatedRun = false,
): void {
useEffect(() => {
const mounted = { current: true };

const effectReleased = new Deferred<void>(true);

const run = preventDuplicatedRun
? async () => {
await nextTick;

Check warning on line 21 in src/react/hook/use-async-effect.ts

View check run for this annotation

Codecov / codecov/patch

src/react/hook/use-async-effect.ts#L20-L21

Added lines #L20 - L21 were not covered by tests
if (!mounted.current) return;
return effectCallback(mounted, effectReleased);

Check warning on line 23 in src/react/hook/use-async-effect.ts

View check run for this annotation

Codecov / codecov/patch

src/react/hook/use-async-effect.ts#L23

Added line #L23 was not covered by tests
}
: () => effectCallback(mounted, effectReleased);

Check warning on line 25 in src/react/hook/use-async-effect.ts

View check run for this annotation

Codecov / codecov/patch

src/react/hook/use-async-effect.ts#L25

Added line #L25 was not covered by tests
if (typeof setImmediate === 'function') {
setImmediate(() => effectCallback(mounted, effectReleased));
setImmediate(run);

Check warning on line 27 in src/react/hook/use-async-effect.ts

View check run for this annotation

Codecov / codecov/patch

src/react/hook/use-async-effect.ts#L27

Added line #L27 was not covered by tests
} else {
setTimeout(() => effectCallback(mounted, effectReleased));
setTimeout(run);

Check warning on line 29 in src/react/hook/use-async-effect.ts

View check run for this annotation

Codecov / codecov/patch

src/react/hook/use-async-effect.ts#L29

Added line #L29 was not covered by tests
}

return () => {
Expand Down
Loading