Skip to content

Let users cancel abortable functions #102

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
29 changes: 22 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,13 @@ export type UseAsyncReturn<
currentParams: Args | null;
};

export type UseAsyncAbortableReturn<
R = UnknownResult,
Args extends any[] = UnknownArgs
> = UseAsyncReturn<R, Args> & {
cancel: () => void;
};

// Relaxed interface which accept both async and sync functions
// Accepting sync function is convenient for useAsyncCallback
const useAsyncInternal = <R = UnknownResult, Args extends any[] = UnknownArgs>(
Expand Down Expand Up @@ -327,9 +334,9 @@ export function useAsync<R = UnknownResult, Args extends any[] = UnknownArgs>(
return useAsyncInternal(asyncFunction, params, options);
}

type AddArg<H, T extends any[]> = ((h: H, ...t: T) => void) extends ((
type AddArg<H, T extends any[]> = ((h: H, ...t: T) => void) extends (
...r: infer R
) => void)
) => void
? R
: never;

Expand All @@ -340,17 +347,22 @@ export const useAsyncAbortable = <
asyncFunction: (...args: AddArg<AbortSignal, Args>) => Promise<R>,
params: Args,
options?: UseAsyncOptions<R>
): UseAsyncReturn<R, Args> => {
): UseAsyncAbortableReturn<R, Args> => {
const abortControllerRef = useRef<AbortController>();

const abortHandler = () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
};

// Wrap the original async function and enhance it with abortion login
const asyncFunctionWrapper: (...args: Args) => Promise<R> = async (
...p: Args
) => {
// Cancel previous async call
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
abortHandler();

// Create/store new abort controller for next async call
const abortController = new AbortController();
abortControllerRef.current = abortController;
Expand All @@ -367,7 +379,10 @@ export const useAsyncAbortable = <
}
};

return useAsync(asyncFunctionWrapper, params, options);
return {
...useAsync(asyncFunctionWrapper, params, options),
cancel: () => abortHandler(),
};
};

// keep compat with TS < 3.5
Expand Down
55 changes: 53 additions & 2 deletions test/useAsync.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
import { useAsync } from '../src';
import { useAsync, useAsyncAbortable } from '../src';
import { renderHook } from '@testing-library/react-hooks';

const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const sleep = (ms: number, signal?: AbortSignal) =>
new Promise((resolve, reject) => {
if (signal && signal.aborted) reject();

const timeout = setTimeout(() => {
resolve(undefined);

if (signal) signal.removeEventListener('abort', abort);
}, ms);

const abort = () => {
if (signal) {
clearTimeout(timeout);
reject();
}
};

if (signal) signal.addEventListener('abort', abort);
});

interface StarwarsHero {
name: string;
Expand Down Expand Up @@ -269,4 +287,37 @@ describe('useAync', () => {
expect(onSuccess).not.toHaveBeenCalled();
expect(onError).toHaveBeenCalled();
});

it('should handle cancel', async () => {
const onSuccess = jest.fn();
const onError = jest.fn();
const onAbort = jest.fn();

const { result, waitForNextUpdate } = renderHook(() =>
useAsyncAbortable(
async (signal: AbortSignal) => {
signal.addEventListener('abort', onAbort);
await sleep(10000, signal);
return fakeResults;
},
[],
{
onSuccess: () => onSuccess(),
onError: () => onError(),
}
)
);

await sleep(10);
expect(result.current.loading).toBe(true);
result.current.cancel();
await waitForNextUpdate();

expect(onAbort).toHaveBeenCalled();
expect(result.current.error).toBeUndefined();
expect(result.current.loading).toBe(false);
expect(result.current.result).toBeUndefined();
expect(onSuccess).not.toHaveBeenCalled();
expect(onError).toHaveBeenCalled();
});
});