Skip to content

Commit 792de4f

Browse files
committed
fixed currentUnit bring it into state
1 parent a717e19 commit 792de4f

File tree

4 files changed

+11
-19
lines changed

4 files changed

+11
-19
lines changed

dist/react-pure-time.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

example/example.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/react-pure-time.tsx

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,26 +19,19 @@ const Time = (props: Props) => {
1919
utc = false,
2020
relativeTime,
2121
} = props;
22-
let currentUnit: string = "";
2322

2423
const [state, setState] = React.useState<State>({
2524
relativeTime: "",
25+
currentUnit: "",
2626
});
2727

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-
3528
React.useEffect(() => {
3629
let interval: null | number = null;
3730
if (props.relativeTime && isDate(props.value) && !interval) {
3831
const date = new Date(props.value);
39-
updateRelativeTime(date, props.unit);
32+
updateRelativeTime(date);
4033
interval = window.setInterval(
41-
() => updateRelativeTime(date, props.unit),
34+
() => updateRelativeTime(date),
4235
getInterval()
4336
);
4437
}
@@ -91,20 +84,17 @@ const Time = (props: Props) => {
9184
};
9285

9386
const getInterval = () => {
87+
const { currentUnit } = state;
9488
if (!currentUnit.length) return 10;
9589
if (!msAmountIn[currentUnit]) return msAmountIn.week;
9690
return msAmountIn[currentUnit];
9791
};
9892

99-
const updateRelativeTime = (date: Date, unit: string): boolean => {
93+
const updateRelativeTime = (date: Date): boolean => {
10094
const diff = getRelativeTimeDiff(date);
95+
state.currentUnit = props.unit || bestFit(diff);
96+
const { currentUnit } = state;
10197

102-
let prevUnit = currentUnit;
103-
currentUnit = unit || bestFit(diff);
104-
if (currentUnit !== prevUnit) {
105-
checkForRelativeTimeProps(props);
106-
return false;
107-
}
10898
const diffkey = `${currentUnit}s` as
10999
| "ms"
110100
| "seconds"
@@ -129,6 +119,7 @@ const Time = (props: Props) => {
129119
}
130120

131121
setState({
122+
...state,
132123
relativeTime: getRelativeTimeString(time, absTime, currentUnit, isFuture),
133124
});
134125
return true;

src/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export type Props = {
1010

1111
export type State = {
1212
relativeTime: string;
13+
currentUnit: string;
1314
};
1415

1516
export type Diff = {

0 commit comments

Comments
 (0)