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

useAsyncFn - return Promise.reject() or Promise.resolve() in the promise resolution #612

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/__tests__/useAsyncFn.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { act, renderHook } from '@testing-library/react-hooks';
import useAsyncFn, { AsyncState } from '../useAsyncFn';

type AdderFn = (a: number, b: number) => Promise<number>;
type FailedPromise = () => Promise<string>;

describe('useAsyncFn', () => {
it('should be defined', () => {
Expand Down Expand Up @@ -47,6 +48,38 @@ describe('useAsyncFn', () => {
});
});

describe('the callback can be awaited and catch thrown error', () => {
let hook;
const failedPromise = (): Promise<string> => Promise.reject('error message');

beforeEach(() => {
hook = renderHook<{ fn: FailedPromise }, [AsyncState<string>, FailedPromise]>(({ fn }) => useAsyncFn(fn), {
initialProps: { fn: failedPromise },
});
});

it('catch errors', async () => {
const [, callback] = hook.result.current;
let error;

await act(async () => {
try {
await callback();
} catch (e) {
error = e;
}
});

expect(error).toEqual('error message');

const [state] = hook.result.current;

expect(state.value).toEqual(undefined);
expect(state.error).toEqual(error);
expect(state.error).toEqual('error message');
});
});

describe('args can be passed to the function', () => {
let hook;
let callCount = 0;
Expand Down
8 changes: 7 additions & 1 deletion src/useAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,14 @@ export default function useAsync<Result = any, Args extends any[] = any[]>(
});

useEffect(() => {
callback();
init();
}, [callback]);

async function init() {
try {
await callback();
} catch {}
}

return state;
}
4 changes: 2 additions & 2 deletions src/useAsyncFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ export default function useAsyncFn<Result = any, Args extends any[] = any[]>(
value => {
isMounted() && set({ value, loading: false });

return value;
return Promise.resolve(value);
},
error => {
isMounted() && set({ error, loading: false });

return error;
return Promise.reject(error);
}
);
}, deps);
Expand Down