All files / src/hooks useLocalToday.ts

100% Statements 16/16
100% Branches 0/0
100% Functions 4/4
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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        67x 67x   23x 24x 24x 24x 24x 24x   23x 23x 23x 23x 23x 23x 23x     67x    
import { useEffect, useState } from 'react'
import { todayDateString } from '@/lib/date'
/** Refresh at local midnight and when returning to a suspended tab. */
export function useLocalToday() {
  const [today, setToday] = useState(todayDateString)
  useEffect(() => {
    let timer: ReturnType<typeof setTimeout>
    const refresh = () => {
      clearTimeout(timer)
      setToday(todayDateString())
      const now = new Date()
      const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
      timer = setTimeout(refresh, midnight.getTime() - now.getTime() + 50)
    }
    refresh()
    window.addEventListener('focus', refresh)
    document.addEventListener('visibilitychange', refresh)
    return () => {
      clearTimeout(timer)
      window.removeEventListener('focus', refresh)
      document.removeEventListener('visibilitychange', refresh)
    }
  }, [])
  return today
}