Skip to content

Commit

Permalink
fix(hooks): short-circuit invalid dates in useTimeAgo hook
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Sep 14, 2022
1 parent 8ae7663 commit 3ff700e
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/sanity/src/hooks/useTimeAgo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,19 @@ export function useTimeAgo(time: Date | string, {minimal, agoSuffix}: TimeAgoOpt
}

function formatRelativeTime(date: Date | string, opts: TimeAgoOpts = {}): TimeSpec {
const now = Date.now()
const parsedDate = date instanceof Date ? date : new Date(date)

// Invalid date? Return empty timestamp and inifinite refresh interval, to save us from
// continuously trying to format an invalid date. The `useEffect` calls in the hook will
// trigger a re-evaluation of the timestamp when the date changes, so this is safe.
if (!parsedDate.getTime()) {
return {
timestamp: '',
refreshInterval: +Infinity,
}
}

const now = Date.now()
const diffMonths = differenceInMonths(now, parsedDate)
const diffYears = differenceInYears(now, parsedDate)

Expand Down

0 comments on commit 3ff700e

Please sign in to comment.