mirror of
https://github.com/ourongxing/newsnow.git
synced 2025-01-19 03:09:14 +08:00
pref: useRelativeTime
This commit is contained in:
parent
b652d73fa6
commit
ef544e5ea0
@ -2,7 +2,6 @@ import type { NewsItem, SourceID, SourceInfo } from "@shared/types"
|
||||
import { OverlayScrollbarsComponent } from "overlayscrollbars-react"
|
||||
import type { UseQueryResult } from "@tanstack/react-query"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { relativeTime } from "@shared/utils"
|
||||
import clsx from "clsx"
|
||||
import { useInView } from "react-intersection-observer"
|
||||
import { useAtom } from "jotai"
|
||||
@ -83,7 +82,6 @@ export function NewsCard({ id, inView, isOverlay, handleListeners }: NewsCardPro
|
||||
placeholderData: prev => prev,
|
||||
staleTime: 1000 * 60 * 5,
|
||||
enabled: inView,
|
||||
refetchOnWindowFocus: true,
|
||||
})
|
||||
|
||||
const addFocusList = useCallback(() => {
|
||||
@ -155,8 +153,9 @@ function Num({ num }: { num: number }) {
|
||||
}
|
||||
|
||||
function ExtraInfo({ item }: { item: NewsItem }) {
|
||||
if (item?.extra?.date) {
|
||||
return relativeTime(item.extra.date)
|
||||
const relativeTime = useRelativeTime(item?.extra?.date)
|
||||
if (relativeTime) {
|
||||
return <>{relativeTime}</>
|
||||
}
|
||||
|
||||
if (item?.extra?.icon) {
|
||||
|
@ -1,17 +1,29 @@
|
||||
import { relativeTime } from "@shared/utils"
|
||||
import { atom, useAtomValue } from "jotai"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
/**
|
||||
* change every minute
|
||||
*/
|
||||
const timerAtom = atom(0)
|
||||
|
||||
timerAtom.onMount = (set) => {
|
||||
const timer = setInterval(() => {
|
||||
set(Date.now())
|
||||
}, 60 * 1000)
|
||||
return () => clearInterval(timer)
|
||||
}
|
||||
|
||||
export function useRelativeTime(timestamp: string | number) {
|
||||
const [time, setTime] = useState<string>()
|
||||
const timer = useAtomValue(timerAtom)
|
||||
|
||||
useEffect(() => {
|
||||
const t = relativeTime(timestamp)
|
||||
if (t) setTime(t)
|
||||
const interval = setInterval(() => {
|
||||
setTime(relativeTime(timestamp))
|
||||
}, 60 * 1000)
|
||||
return () => clearInterval(interval)
|
||||
}, [timestamp])
|
||||
if (t) {
|
||||
setTime(t)
|
||||
}
|
||||
}, [timestamp, timer])
|
||||
|
||||
return time
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user