All files / owid-grapher/site/covid LastUpdated.tsx

42.42% Statements 28/66
100% Branches 0/0
0% Functions 0/1
42.42% Lines 28/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                             1x
import React, { useEffect, useState } from "react"
import dayjs, { Dayjs } from "dayjs"
import relativeTime from "dayjs/plugin/relativeTime"
import { fetchWithRetries } from "../../clientUtils/Util"
dayjs.extend(relativeTime)
 
export interface LastUpdatedTokenProps {
    timestampUrl?: string
}
 
export const LastUpdated = ({ timestampUrl }: LastUpdatedTokenProps) => {
    const [date, setDate] = useState<null | Dayjs>(null)
    useEffect(() => {
        const fetchTimeStamp = async () => {
            if (!timestampUrl) return
            const response = await fetchWithRetries(timestampUrl)
            if (!response.ok) return
            const timestampRaw = await response.text()
            const timestamp = timestampRaw.trim()
            const parsedDate =
                timestamp.length < 20
                    ? dayjs(`${timestamp}Z`)
                    : dayjs(timestamp)

            if (!parsedDate.isValid()) return
            setDate(parsedDate)
        }
        fetchTimeStamp()
    }, [])

    return (
        date && (
            <span>
                Last update: <strong>{date.fromNow()}</strong>.
                {/* (
                {date.toDate().toLocaleString("en-US", {
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                    hour: "numeric",
                    minute: "2-digit",
                    timeZone: "UTC",
                    timeZoneName: "short",
                })}
                ) */}
            </span>
        )
    )
}