Skip to content

Commit

Permalink
fix(useCountdown): fix TS type definition for DateLike
Browse files Browse the repository at this point in the history
  • Loading branch information
vikiboss committed Oct 24, 2024
1 parent e38f438 commit 3615692
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions packages/react-use/src/use-countdown/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,23 +53,30 @@ export type UseCountdownReturns<Controls extends boolean> = Controls extends tru
? { ms: number; isStop: boolean } & Pausable
: number

function calRemainingTime(date: Gettable<DateLike>) {
function calRemainingTime(date: Gettable<DateLike | null | undefined>) {
const dateValue = unwrapGettable(date)

if (noNullish(dateValue)) {
return Math.max(0, normalizeDate(dateValue).getTime() - now())
}

return 0
}

/**
* A React Hook that provides a countdown timer.
*/
export function useCountdown(date: Gettable<DateLike>): UseCountdownReturns<false>
export function useCountdown(date: Gettable<DateLike>, options: UseCountdownOptions<false>): UseCountdownReturns<false>
export function useCountdown(date: Gettable<DateLike>, options: UseCountdownOptions<true>): UseCountdownReturns<true>
export function useCountdown(date: Gettable<DateLike | null | undefined>): UseCountdownReturns<false>
export function useCountdown(
date: Gettable<DateLike | null | undefined>,
options: UseCountdownOptions<false>,
): UseCountdownReturns<false>
export function useCountdown(
date: Gettable<DateLike>,
date: Gettable<DateLike | null | undefined>,
options: UseCountdownOptions<true>,
): UseCountdownReturns<true>
export function useCountdown(
date: Gettable<DateLike | null | undefined>,
options: UseCountdownOptions<boolean> = {},
): UseCountdownReturns<boolean> {
const {
Expand All @@ -78,17 +85,14 @@ export function useCountdown(
interval = 'requestAnimationFrame',
onStop,
onUpdate,
} = options || {}
} = options

const [ms, setMs] = useSafeState(() => calRemainingTime(date))

const update = useStableFn(() => {
const { date, onUpdate, onStop } = latest.current
const ms = calRemainingTime(date)

// ignore same value when use `requestAnimationFrame` or smaller interval
if (latest.current.ms === ms) return

onUpdate?.(ms, Math.ceil(ms / 1000))

if (ms === 0) {
Expand Down

0 comments on commit 3615692

Please sign in to comment.