Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix memory leak #163

Merged
merged 1 commit into from
Jun 10, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 16 additions & 26 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// @flow

import * as React from 'react'
import { useCallback, useEffect, useState } from 'react'
import defaultFormatter from './defaultFormatter'
import { useEffect, useState } from 'react'
import dateParser from './dateParser'
import defaultFormatter from './defaultFormatter'

export type Unit =
| 'second'
Expand Down Expand Up @@ -65,22 +65,20 @@ export default function TimeAgo({
minPeriod = 0,
maxPeriod = WEEK,
title,
now = () => Date.now(),
now = Date.now,
...passDownProps
}: Props): null | React.MixedElement {
const forceUpdate = useUpdate()
const [timeNow, setTimeNow] = useState(now())
useEffect(() => {
if (!live) {
return
}
let timeoutId
const tick = (refresh: ?boolean): void => {
const tick = (): number => {
const then = dateParser(date).valueOf()
if (!then) {
console.warn('[react-timeago] Invalid Date provided')
return
return 0
}
const timeNow = now()
const seconds = Math.round(Math.abs(timeNow - then) / 1000)

const unboundPeriod =
Expand All @@ -98,28 +96,27 @@ export default function TimeAgo({
)

if (period) {
if (timeoutId) {
clearTimeout(timeoutId)
}
timeoutId = setTimeout(tick, period)
}
if (!refresh) {
forceUpdate()
return setTimeout(() => {
setTimeNow(now())
}, period)
}

return 0
}
tick(true)
const timeoutId = tick()
return () => {
clearTimeout(timeoutId)
if (timeoutId) {
clearTimeout(timeoutId)
}
}
}, [date, forceUpdate, live, maxPeriod, minPeriod, now])
}, [date, live, maxPeriod, minPeriod, now, timeNow])

const Komponent = component
const then = dateParser(date).valueOf()
if (!then) {
return null
}

const timeNow = now()
const seconds = Math.round(Math.abs(timeNow - then) / 1000)
const suffix = then < timeNow ? 'ago' : 'from now'

Expand Down Expand Up @@ -158,10 +155,3 @@ export default function TimeAgo({
</Komponent>
)
}

function useUpdate(): () => void {
const [_, setCount] = useState(0)
return useCallback(() => {
setCount((num) => num + 1)
}, [])
}