about summary refs log tree commit diff
path: root/src/view/com/util/TimeElapsed.tsx
blob: a4958518260c1aeda4b2449573a4ed90560fe918 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React from 'react'

import {useGetTimeAgo} from '#/lib/hooks/useTimeAgo'
import {useTickEveryMinute} from '#/state/shell'

export function TimeElapsed({
  timestamp,
  children,
  timeToString,
}: {
  timestamp: string
  children: ({timeElapsed}: {timeElapsed: string}) => JSX.Element
  timeToString?: (timeElapsed: string) => string
}) {
  const ago = useGetTimeAgo()
  const format = timeToString ?? ago
  const tick = useTickEveryMinute()
  const [timeElapsed, setTimeAgo] = React.useState(() =>
    format(timestamp, tick),
  )

  const [prevTick, setPrevTick] = React.useState(tick)
  if (prevTick !== tick) {
    setPrevTick(tick)
    setTimeAgo(format(timestamp, tick))
  }

  return children({timeElapsed})
}