Refactored views component and removed image

This commit is contained in:
r-freeman 2023-01-18 21:36:47 +00:00
parent 2f098f1429
commit a7784789fd
2 changed files with 6 additions and 12 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 291 KiB

View File

@ -1,33 +1,27 @@
import {ElementType, useEffect} from 'react'
import useSWR from 'swr'
import useSWRImmutable from 'swr/immutable'
import fetcher from '@/lib/fetcher'
function numberFormat(value: number) {
return new Intl.NumberFormat('en', {
notation: 'compact'
}).format(value)
}
type ViewsType = {
views: string
}
const updateViews = (slug: string) => fetcher(`/api/views/${slug}`, {method: 'POST'})
export function Views({as: Component = 'span', slug}: { as?: ElementType, slug: string }) {
const {data} = useSWR<ViewsType>(`/api/views/${slug}`, fetcher)
const {data} = useSWRImmutable(`/api/views/${slug}`, fetcher)
const views = Number(data?.views)
useEffect(() => {
const registerView = () =>
fetch(`/api/views/${slug}`, {
method: 'POST'
})
registerView().then(r => r)
updateViews(slug).then(r => r)
}, [slug])
return (
<Component>
{views > 0 ? ` · ${numberFormat(views)} views` : ''}
{` · ${views > 0 ? numberFormat(views) : '---'} views`}
</Component>
)
}