Skip to content

Commit a7b9ea1

Browse files
Merge pull request #31 from 2wheeh/fix/reset-use-async
fix: clear states when enabled is set to false in useAsync hook
2 parents 97aa326 + b20f8ca commit a7b9ea1

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

packages/react/__tests__/hooks/useAsync.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,32 @@ describe('useAsync', () => {
127127
expect(result.current.error).toBeNull();
128128
expect(queryFn).not.toHaveBeenCalled();
129129
});
130+
131+
it('should clear states on enabled change to false', async () => {
132+
const queryFn = jest.fn().mockResolvedValue('data');
133+
134+
const { result, rerender } = renderHook(
135+
({ enabled }) =>
136+
useAsync({
137+
queryKey: 'test7',
138+
queryFn,
139+
enabled,
140+
}),
141+
{
142+
initialProps: { enabled: true },
143+
}
144+
);
145+
146+
await waitFor(() => {
147+
expect(result.current.isLoading).toBe(false);
148+
});
149+
150+
expect(result.current.data).toBe('data');
151+
152+
rerender({ enabled: false });
153+
154+
expect(result.current.data).toBeNull();
155+
expect(result.current.isLoading).toBe(false);
156+
expect(result.current.error).toBeNull();
157+
});
130158
});

packages/react/src/hooks/useAsync.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,14 @@ export function useAsync<T>({
6060
}, []);
6161

6262
useEffect(() => {
63-
if (!enabled) return;
63+
if (!enabled) {
64+
setState({
65+
data: null,
66+
isLoading: false,
67+
error: null,
68+
});
69+
return;
70+
}
6471

6572
if (!disableCache && cache.has(cacheKey)) {
6673
setState(prev => ({

0 commit comments

Comments
 (0)