Skip to content

Commit

Permalink
[base] Support updated timestamps in useTimeAgo
Browse files Browse the repository at this point in the history
- Simplify the code by using setState instead of useReducer
- Listen to changes to time/opts and re-calculate
  • Loading branch information
judofyr authored and rexxars committed Oct 6, 2020
1 parent 644f127 commit c8b6211
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions packages/@sanity/base/src/time/useTimeAgo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {useEffect, useReducer} from 'react'
import {useEffect, useReducer, useMemo, useState} from 'react'
import {
format,
differenceInSeconds,
Expand All @@ -25,9 +25,11 @@ interface TimeAgoOpts {
}

export function useTimeAgo(time: Date | string, opts: TimeAgoOpts = {}): string {
const [resolved, setResolved] = useReducer(reduceState, null, () =>
formatRelativeTime(time, opts)
)
const [resolved, setResolved] = useState(() => formatRelativeTime(time, opts))

useEffect(() => {
setResolved(formatRelativeTime(time, opts))
}, [time, opts.minimal])

useEffect(() => {
const id: number | undefined = Number.isFinite(resolved.refreshInterval)
Expand All @@ -38,17 +40,11 @@ export function useTimeAgo(time: Date | string, opts: TimeAgoOpts = {}): string
: undefined

return () => clearInterval(id)
}, [time, resolved.refreshInterval])
}, [time, opts.minimal, resolved.refreshInterval])

return resolved.timestamp
}

function reduceState(prev: TimeSpec, next: TimeSpec) {
return prev.timestamp === next.timestamp && prev.refreshInterval === next.refreshInterval
? prev
: next
}

// eslint-disable-next-line complexity
function formatRelativeTime(date: Date | string, opts: TimeAgoOpts = {}): TimeSpec {
const now = Date.now()
Expand Down

0 comments on commit c8b6211

Please sign in to comment.