portfolio/src/components/Views.tsx

27 lines
750 B
TypeScript
Raw Normal View History

2023-01-17 21:24:16 +00:00
import {ElementType, useEffect} from 'react'
import useSWRImmutable from 'swr/immutable'
2023-01-17 21:24:16 +00:00
import fetcher from '@/lib/fetcher'
2023-01-17 21:24:16 +00:00
function numberFormat(value: number) {
return new Intl.NumberFormat('en', {
notation: 'compact'
}).format(value)
}
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 }) {
const {data} = useSWRImmutable(`/api/views/${slug}`, fetcher)
2023-01-17 21:24:16 +00:00
const views = Number(data?.views)
useEffect(() => {
updateViews(slug).then(r => r)
2023-01-17 21:24:16 +00:00
}, [slug])
return (
<Component>
{` · ${views > 0 ? numberFormat(views) : '---'} views`}
2023-01-17 21:24:16 +00:00
</Component>
)
}