From ef544e5ea0b14d4246730390c2188bec876dd8a7 Mon Sep 17 00:00:00 2001 From: Ou Date: Sat, 5 Oct 2024 02:29:05 +0800 Subject: [PATCH] pref: useRelativeTime --- src/components/section/Card.tsx | 7 +++---- src/hooks/useRelativeTime.ts | 24 ++++++++++++++++++------ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/components/section/Card.tsx b/src/components/section/Card.tsx index 8baff18..a5ecead 100644 --- a/src/components/section/Card.tsx +++ b/src/components/section/Card.tsx @@ -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) { diff --git a/src/hooks/useRelativeTime.ts b/src/hooks/useRelativeTime.ts index 9bf5f4c..ec5a35b 100644 --- a/src/hooks/useRelativeTime.ts +++ b/src/hooks/useRelativeTime.ts @@ -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() + 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 }