CoastalCommitsPastes/client/components/badges/expiration-badge/index.tsx

67 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-04-09 20:48:19 -04:00
import { Badge, Tooltip } from "@geist-ui/core"
import { timeUntil } from "@lib/time-ago"
import { useCallback, useEffect, useMemo, useState } from "react"
const ExpirationBadge = ({
2022-04-09 20:48:19 -04:00
postExpirationDate
}: // onExpires
{
postExpirationDate: Date | string | null
onExpires?: () => void
}) => {
2022-04-09 20:48:19 -04:00
const expirationDate = useMemo(
() => (postExpirationDate ? new Date(postExpirationDate) : null),
[postExpirationDate]
)
const [timeUntilString, setTimeUntil] = useState<string | null>(
expirationDate ? timeUntil(expirationDate) : null
)
useEffect(() => {
let interval: NodeJS.Timer | null = null
if (expirationDate) {
interval = setInterval(() => {
if (expirationDate) {
setTimeUntil(timeUntil(expirationDate))
}
}, 1000)
}
return () => {
if (interval) {
clearInterval(interval)
}
}
}, [expirationDate])
const isExpired = useMemo(() => {
return timeUntilString && timeUntilString === "in 0 seconds"
}, [timeUntilString])
// useEffect(() => {
// // check if expired every
// if (isExpired) {
// if (onExpires) {
// onExpires();
// }
// }
// }, [isExpired, onExpires])
if (!expirationDate) {
return null
}
return (
<Badge type={isExpired ? "error" : "warning"}>
<Tooltip
hideArrow
text={`${expirationDate.toLocaleDateString()} ${expirationDate.toLocaleTimeString()}`}
>
{isExpired ? "Expired" : `Expires ${timeUntilString}`}
</Tooltip>
</Badge>
)
}
2022-04-09 20:48:19 -04:00
export default ExpirationBadge