Skip to content

Commit dac66b2

Browse files
committed
fix: 修复重置 loadingDelay 为 undefined 后,定时器没有被清理而导致 loading 始终为 true 的 bug
1 parent c7bb04c commit dac66b2

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed

packages/hooks/src/useRequest/__tests__/useLoadingDelayPlugin.test.ts

+27-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { act, renderHook, waitFor } from '@testing-library/react';
22
import type { RenderHookResult } from '@testing-library/react';
33
import useRequest from '../index';
4-
import { request } from '../../utils/testingHelpers';
4+
import { request, sleep } from '../../utils/testingHelpers';
55

66
describe('useLoadingDelayPlugin', () => {
77
jest.useFakeTimers();
@@ -75,4 +75,30 @@ describe('useLoadingDelayPlugin', () => {
7575

7676
await waitFor(() => expect(hook.result.current.loading).toBe(true));
7777
});
78+
79+
it.only('useLoadingDelayPlugin should update loading when loadingDelay is reset and refreshDeps is changed', async () => {
80+
jest.useRealTimers();
81+
82+
let loadingDelay: number | null = 1500;
83+
84+
act(() => {
85+
hook = setUp(request, {
86+
loadingDelay,
87+
});
88+
});
89+
90+
expect(hook.result.current.loading).toBe(false);
91+
92+
loadingDelay = null;
93+
94+
hook.rerender({
95+
loadingDelay,
96+
});
97+
98+
await act(async () => {
99+
await sleep(1600);
100+
});
101+
102+
expect(hook.result.current.loading).toBe(false);
103+
});
78104
});

packages/hooks/src/useRequest/src/plugins/useLoadingDelayPlugin.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,17 @@ import type { Plugin, Timeout } from '../types';
44
const useLoadingDelayPlugin: Plugin<any, any[]> = (fetchInstance, { loadingDelay, ready }) => {
55
const timerRef = useRef<Timeout>();
66

7-
if (!loadingDelay) {
8-
return {};
9-
}
10-
117
const cancelTimeout = () => {
128
if (timerRef.current) {
139
clearTimeout(timerRef.current);
1410
}
1511
};
1612

13+
if (!loadingDelay) {
14+
cancelTimeout();
15+
return {};
16+
}
17+
1718
return {
1819
onBefore: () => {
1920
cancelTimeout();

0 commit comments

Comments
 (0)