2023-01-17 21:24:16 +00:00
|
|
|
import {ElementType, useEffect} from 'react'
|
2023-01-18 21:36:47 +00:00
|
|
|
import useSWRImmutable from 'swr/immutable'
|
2023-01-17 21:24:16 +00:00
|
|
|
import fetcher from '@/lib/fetcher'
|
|
|
|
|
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-18 21:36:47 +00:00
|
|
|
const {data} = useSWRImmutable(`/api/views/${slug}`, fetcher)
|
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-18 21:36:47 +00:00
|
|
|
{` · ${views > 0 ? numberFormat(views) : '---'} views`}
|
2023-01-17 21:24:16 +00:00
|
|
|
</Component>
|
|
|
|
)
|
|
|
|
}
|