Skip to content

Commit

Permalink
fix: 修复重置 loadingDelay 为 undefined 后,定时器没有被清理而导致 loading 始终为 true 的 bug
Browse files Browse the repository at this point in the history
  • Loading branch information
guaijie committed Jan 21, 2025
1 parent c7bb04c commit 497fa13
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"clean-dist": "rimraf 'packages/*/{lib,es,node_modules,dist}'",
"clean": "pnpm run clean-dist && rimraf node_modules",
"build": "pnpm -r --filter=./packages/* run build",
"test": "jest",
"test": "jest useLoadingDelayPlugin",
"coveralls": "jest --coverage --coverageReporters=text-lcov | coveralls",
"lint": "eslint --ignore-pattern **/__tests__/* --ignore-pattern **/demo/* \"packages/*/src/**/*.{ts,tsx}\" --cache",
"pretty": "biome format --fix --staged",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import type { RenderHookResult } from '@testing-library/react';
import useRequest from '../index';
import { request } from '../../utils/testingHelpers';
import { request, sleep } from '../../utils/testingHelpers';

describe('useLoadingDelayPlugin', () => {
jest.useFakeTimers();
Expand Down Expand Up @@ -75,4 +75,30 @@ describe('useLoadingDelayPlugin', () => {

await waitFor(() => expect(hook.result.current.loading).toBe(true));
});

it.only('useLoadingDelayPlugin should update loading when loadingDelay is reset and refreshDeps is changed', async () => {
jest.useRealTimers();

let loadingDelay: number | null = 1500;

act(() => {
hook = setUp(request, {
loadingDelay,
});
});

expect(hook.result.current.loading).toBe(false);

loadingDelay = null;

hook.rerender({
loadingDelay,
});

await act(async () => {
await sleep(1600);
});

expect(hook.result.current.loading).toBe(false);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@ import type { Plugin, Timeout } from '../types';
const useLoadingDelayPlugin: Plugin<any, any[]> = (fetchInstance, { loadingDelay, ready }) => {
const timerRef = useRef<Timeout>();

if (!loadingDelay) {
return {};
}

const cancelTimeout = () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};

if (!loadingDelay) {
cancelTimeout();
return {};
}

return {
onBefore: () => {
cancelTimeout();
Expand Down

0 comments on commit 497fa13

Please sign in to comment.