fix: Recalculate time ago on re-render (#4107)
This commit is contained in:
@@ -11,13 +11,17 @@ const calculateTimeAgo = (timestamp: Date) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const useTimeAgo = (timestamp: Date, updateFrequency = 1000) => {
|
export const useTimeAgo = (timestamp: Date, updateFrequency = 1000) => {
|
||||||
const [timeAgo, setTimeAgo] = useState(calculateTimeAgo(timestamp));
|
const [timeAgo, setTimeAgo] = useState(() => calculateTimeAgo(timestamp));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setTimeAgo(calculateTimeAgo(timestamp));
|
||||||
|
}, [timestamp]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const intervalId = setInterval(() => setTimeAgo(calculateTimeAgo(timestamp)), updateFrequency);
|
const intervalId = setInterval(() => setTimeAgo(calculateTimeAgo(timestamp)), updateFrequency);
|
||||||
|
|
||||||
return () => clearInterval(intervalId); // clear interval on hook unmount
|
return () => clearInterval(intervalId); // clear interval on hook unmount
|
||||||
}, [timestamp]);
|
}, [timestamp, updateFrequency]);
|
||||||
|
|
||||||
return timeAgo;
|
return timeAgo;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user