Skip to content

Commit

Permalink
fix(useCountDown): targetDate resets leftTime (#2346)
Browse files Browse the repository at this point in the history
  • Loading branch information
joe-leong authored and raotaohub committed Mar 28, 2024
1 parent 85eaf13 commit 48bebdd
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
29 changes: 28 additions & 1 deletion packages/hooks/src/useCountDown/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { act, renderHook } from '@testing-library/react';
import useCountDown, { Options } from '../index';
import type { Options } from '../index';
import useCountDown from '../index';

const setup = (options: Options = {}) =>
renderHook((props: Options = options) => useCountDown(props));
Expand Down Expand Up @@ -235,4 +236,30 @@ describe('useCountDown', () => {
const { result } = setup({ leftTime: -5 * 1000 });
expect(result.current[0]).toBe(0);
});

it('run with timeLeft should not be reset after targetDate changed', async () => {
let targetDate = Date.now() + 8000;

const { result, rerender } = setup({
leftTime: 6000,
targetDate,
});
expect(result.current[0]).toBe(6000);

act(() => {
jest.advanceTimersByTime(2000);
});
rerender({
leftTime: 6000,
targetDate: targetDate,
});
expect(result.current[0]).toBe(4000);

targetDate = Date.now() + 9000;
rerender({
leftTime: 6000,
targetDate: targetDate,
});
expect(result.current[0]).toBe(4000);
});
});
12 changes: 5 additions & 7 deletions packages/hooks/src/useCountDown/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,11 @@ const parseMs = (milliseconds: number): FormattedRes => {
const useCountdown = (options: Options = {}) => {
const { leftTime, targetDate, interval = 1000, onEnd } = options || {};

const target = useMemo<TDate>(() => {
if ('leftTime' in options) {
return isNumber(leftTime) && leftTime > 0 ? Date.now() + leftTime : undefined;
} else {
return targetDate;
}
}, [leftTime, targetDate]);
const memoLeftTime = useMemo<TDate>(() => {
return isNumber(leftTime) && leftTime > 0 ? Date.now() + leftTime : undefined;
}, [leftTime]);

const target = 'leftTime' in options ? memoLeftTime : targetDate;

const [timeLeft, setTimeLeft] = useState(() => calcLeft(target));

Expand Down

0 comments on commit 48bebdd

Please sign in to comment.