Skip to content

Commit

Permalink
fix: loading is always return true when set loadingDelay (#1903)
Browse files Browse the repository at this point in the history
* fix: loading is always return true when set loadingDelay

* perf: optimize judgment conditions

* perf: optimize judgment conditions
  • Loading branch information
hchlq committed Feb 3, 2023
1 parent 056f347 commit 6db48a7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,35 @@ describe('useLoadingDelayPlugin', () => {
await waitFor(() => expect(hook.result.current.loading).toEqual(false));
expect(hook.result.current.loading).toEqual(false);
});

it('useLoadingDelayPlugin should no update loading when ready is false', async () => {
act(() => {
hook = setUp(request, {
loadingDelay: 2000,
ready: false,
});
});
expect(hook.result.current.loading).toEqual(false);

act(() => {
jest.advanceTimersByTime(3000);
});

expect(hook.result.current.loading).toEqual(false);
});

it('useLoadingDelayPlugin should update loading when ready is undefined', async () => {
act(() => {
hook = setUp(request, {
loadingDelay: 2000,
});
});
expect(hook.result.current.loading).toEqual(false);

act(() => {
jest.advanceTimersByTime(3000);
});

expect(hook.result.current.loading).toEqual(true);
});
});
18 changes: 12 additions & 6 deletions packages/hooks/src/useRequest/src/plugins/useLoadingDelayPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useRef } from 'react';
import type { Plugin, Timeout } from '../types';
import { isBoolean } from '../../../utils';

const useLoadingDelayPlugin: Plugin<any, any[]> = (fetchInstance, { loadingDelay }) => {
const useLoadingDelayPlugin: Plugin<any, any[]> = (fetchInstance, { loadingDelay, ready }) => {
const timerRef = useRef<Timeout>();

if (!loadingDelay) {
Expand All @@ -18,11 +19,16 @@ const useLoadingDelayPlugin: Plugin<any, any[]> = (fetchInstance, { loadingDelay
onBefore: () => {
cancelTimeout();

timerRef.current = setTimeout(() => {
fetchInstance.setState({
loading: true,
});
}, loadingDelay);
// Two cases:
// 1. ready === undefined
// 2. ready === true
if (ready !== false) {
timerRef.current = setTimeout(() => {
fetchInstance.setState({
loading: true,
});
}, loadingDelay);
}

return {
loading: false,
Expand Down

0 comments on commit 6db48a7

Please sign in to comment.