|
1 | 1 | import { useState, useEffect, useRef } from 'react'; |
| 2 | +import { Time } from './utils'; |
2 | 3 |
|
3 | 4 | export default function useTime(settings) { |
4 | 5 | const { format } = settings || {}; |
5 | 6 |
|
6 | | - const [seconds, setSeconds] = useState(0); |
7 | | - const [minutes, setMinutes] = useState(0); |
8 | | - const [hours, setHours] = useState(0); |
9 | | - const [ampm, setAmPm] = useState(''); |
| 7 | + const [seconds, setSeconds] = useState(Time.getSecondsFromTimeNow()); |
10 | 8 | const intervalRef = useRef(); |
11 | 9 |
|
12 | | - function formatHours(hoursValue) { |
13 | | - if (format === '12-hour') { |
14 | | - const ampmValue = hoursValue >= 12 ? 'pm' : 'am'; |
15 | | - let formattedHours = hoursValue % 12; |
16 | | - formattedHours = formattedHours || 12; |
17 | | - return { hoursValue: formattedHours, ampmValue }; |
| 10 | + function clearIntervalRef() { |
| 11 | + if (intervalRef.current) { |
| 12 | + clearInterval(intervalRef.current); |
| 13 | + intervalRef.current = undefined; |
18 | 14 | } |
19 | | - return { hoursValue, ampmValue: '' }; |
20 | 15 | } |
21 | 16 |
|
22 | | - function setCurrentTime() { |
23 | | - const now = new Date(); |
24 | | - const secondsValue = now.getSeconds(); |
25 | | - const minutesValue = now.getMinutes(); |
26 | | - const { hoursValue, ampmValue } = formatHours(now.getHours()); |
27 | | - |
28 | | - setSeconds(secondsValue); |
29 | | - setMinutes(minutesValue); |
30 | | - setHours(hoursValue); |
31 | | - setAmPm(ampmValue); |
32 | | - } |
33 | | - |
34 | | - |
35 | 17 | function start() { |
36 | 18 | if (!intervalRef.current) { |
37 | | - setCurrentTime(); |
38 | | - intervalRef.current = setInterval(() => setCurrentTime(), 1000); |
39 | | - } |
40 | | - } |
41 | | - |
42 | | - function reset() { |
43 | | - if (intervalRef.current) { |
44 | | - clearInterval(intervalRef.current); |
45 | | - intervalRef.current = undefined; |
| 19 | + intervalRef.current = setInterval(() => setSeconds(Time.getSecondsFromTimeNow()), 1000); |
46 | 20 | } |
47 | | - setSeconds(0); |
48 | | - setMinutes(0); |
49 | | - setHours(0); |
50 | | - setAmPm(''); |
51 | 21 | } |
52 | 22 |
|
53 | 23 | // didMount effect |
54 | 24 | useEffect(() => { |
55 | 25 | start(); |
56 | | - return reset; |
| 26 | + return clearIntervalRef; |
57 | 27 | }, []); |
58 | 28 |
|
59 | 29 |
|
60 | 30 | return { |
61 | | - seconds, minutes, hours, ampm, |
| 31 | + ...Time.getFormattedTimeFromSeconds(seconds, format), |
62 | 32 | }; |
63 | 33 | } |
0 commit comments