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