Skip to content

Commit 51a02e2

Browse files
committed
JS: missing params deps array => fallback to [] to prevent infinite loop
1 parent 7099f8b commit 51a02e2

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,11 @@ const useAsyncInternal = <R = UnknownResult, Args extends any[] = UnknownArgs>(
231231
params: Args,
232232
options?: UseAsyncOptions<R>
233233
): UseAsyncReturn<R, Args> => {
234+
// Fallback missing params, only for JS users forgetting the deps array, to prevent infinite loops
235+
// https://github.com/slorber/react-async-hook/issues/27
236+
// @ts-ignore
237+
!params && (params = []);
238+
234239
const normalizedOptions = normalizeOptions<R>(options);
235240

236241
const [currentParams, setCurrentParams] = useState<Args | null>(null);

test/useAsync.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,26 @@ describe('useAync', () => {
9393
expect(onError).not.toHaveBeenCalled();
9494
});
9595

96+
// See https://github.com/slorber/react-async-hook/issues/27
97+
it('should handle async function without dependency array (shortcut) ', async () => {
98+
const getFakeResultsAsync = () => Promise.resolve(fakeResults);
99+
100+
const { result, waitForNextUpdate } = renderHook(() =>
101+
// It is better to always required a deps array for TS users, but JS users might forget it so...
102+
// Should we allow this "shortcut" for TS users too? I'd rather not
103+
// @ts-ignore
104+
useAsync(getFakeResultsAsync)
105+
);
106+
107+
expect(result.current.loading).toBe(true);
108+
109+
await waitForNextUpdate();
110+
111+
expect(result.current.result).toEqual(fakeResults);
112+
expect(result.current.loading).toBe(false);
113+
expect(result.current.error).toBeUndefined();
114+
});
115+
96116
it('should resolve a successful real-world requests with potential race conditions', async () => {
97117
const onSuccess = jest.fn();
98118
const onError = jest.fn();

0 commit comments

Comments
 (0)