2023-01-17 21:24:16 +00:00
|
|
|
import {ElementType, useEffect} from 'react'
|
|
|
|
import fetcher from '@/lib/fetcher'
|
2023-01-19 12:56:26 +00:00
|
|
|
import useSWR from 'swr'
|
2023-01-17 21:24:16 +00:00
|
|
|
|
2023-01-19 12:56:26 +00:00
|
|
|
type ViewsType = {
|
|
|
|
views: string
|
|
|
|
}
|
2023-01-18 21:36:47 +00:00
|
|
|
|
2023-01-17 21:24:16 +00:00
|
|
|
function numberFormat(value: number) {
|
|
|
|
return new Intl.NumberFormat('en', {
|
|
|
|
notation: 'compact'
|
|
|
|
}).format(value)
|
|
|
|
}
|
|
|
|
|
2023-01-18 21:36:47 +00:00
|
|
|
const updateViews = (slug: string) => fetcher(`/api/views/${slug}`, {method: 'POST'})
|
2023-01-17 21:24:16 +00:00
|
|
|
|
|
|
|
export function Views({as: Component = 'span', slug}: { as?: ElementType, slug: string }) {
|
2023-01-19 12:56:26 +00:00
|
|
|
const {data} = useSWR<ViewsType>(`/api/views/${slug}`, fetcher, {
|
|
|
|
revalidateOnFocus: false,
|
|
|
|
revalidateOnMount: true
|
|
|
|
})
|
2023-01-17 21:24:16 +00:00
|
|
|
const views = Number(data?.views)
|
|
|
|
|
|
|
|
useEffect(() => {
|
2023-01-18 21:36:47 +00:00
|
|
|
updateViews(slug).then(r => r)
|
2023-01-17 21:24:16 +00:00
|
|
|
}, [slug])
|
|
|
|
|
|
|
|
return (
|
|
|
|
<Component>
|
2023-01-19 12:56:26 +00:00
|
|
|
{` · ${views > 0 ? numberFormat(views) : '—'} views`}
|
2023-01-17 21:24:16 +00:00
|
|
|
</Component>
|
|
|
|
)
|
|
|
|
}
|