@@ -19,26 +19,19 @@ const Time = (props: Props) => {
19
19
utc = false ,
20
20
relativeTime,
21
21
} = props ;
22
- let currentUnit : string = "" ;
23
22
24
23
const [ state , setState ] = React . useState < State > ( {
25
24
relativeTime : "" ,
25
+ currentUnit : "" ,
26
26
} ) ;
27
27
28
- const checkForRelativeTimeProps = ( props : Props ) : void => {
29
- if ( props . relativeTime && isDate ( props . value ) ) {
30
- const date = new Date ( props . value ) ;
31
- updateRelativeTime ( date , props . unit ) ;
32
- }
33
- } ;
34
-
35
28
React . useEffect ( ( ) => {
36
29
let interval : null | number = null ;
37
30
if ( props . relativeTime && isDate ( props . value ) && ! interval ) {
38
31
const date = new Date ( props . value ) ;
39
- updateRelativeTime ( date , props . unit ) ;
32
+ updateRelativeTime ( date ) ;
40
33
interval = window . setInterval (
41
- ( ) => updateRelativeTime ( date , props . unit ) ,
34
+ ( ) => updateRelativeTime ( date ) ,
42
35
getInterval ( )
43
36
) ;
44
37
}
@@ -91,20 +84,17 @@ const Time = (props: Props) => {
91
84
} ;
92
85
93
86
const getInterval = ( ) => {
87
+ const { currentUnit } = state ;
94
88
if ( ! currentUnit . length ) return 10 ;
95
89
if ( ! msAmountIn [ currentUnit ] ) return msAmountIn . week ;
96
90
return msAmountIn [ currentUnit ] ;
97
91
} ;
98
92
99
- const updateRelativeTime = ( date : Date , unit : string ) : boolean => {
93
+ const updateRelativeTime = ( date : Date ) : boolean => {
100
94
const diff = getRelativeTimeDiff ( date ) ;
95
+ state . currentUnit = props . unit || bestFit ( diff ) ;
96
+ const { currentUnit } = state ;
101
97
102
- let prevUnit = currentUnit ;
103
- currentUnit = unit || bestFit ( diff ) ;
104
- if ( currentUnit !== prevUnit ) {
105
- checkForRelativeTimeProps ( props ) ;
106
- return false ;
107
- }
108
98
const diffkey = `${ currentUnit } s` as
109
99
| "ms"
110
100
| "seconds"
@@ -129,6 +119,7 @@ const Time = (props: Props) => {
129
119
}
130
120
131
121
setState ( {
122
+ ...state ,
132
123
relativeTime : getRelativeTimeString ( time , absTime , currentUnit , isFuture ) ,
133
124
} ) ;
134
125
return true ;
0 commit comments