Updated views component

This commit is contained in:
r-freeman 2023-01-19 12:56:26 +00:00
parent a7784789fd
commit 25c41021cb
2 changed files with 18 additions and 3 deletions

View File

@ -36,6 +36,15 @@ const nextConfig = {
value: "s-maxage=1, stale-while-revalidate=59"
}
]
},
{
source: '/api/views/:slug',
headers: [
{
key: "Cache-Control",
value: "public, max-age=0, must-revalidate"
}
]
}
]
}

View File

@ -1,7 +1,10 @@
import {ElementType, useEffect} from 'react'
import useSWRImmutable from 'swr/immutable'
import fetcher from '@/lib/fetcher'
import useSWR from 'swr'
type ViewsType = {
views: string
}
function numberFormat(value: number) {
return new Intl.NumberFormat('en', {
@ -12,7 +15,10 @@ function numberFormat(value: number) {
const updateViews = (slug: string) => fetcher(`/api/views/${slug}`, {method: 'POST'})
export function Views({as: Component = 'span', slug}: { as?: ElementType, slug: string }) {
const {data} = useSWRImmutable(`/api/views/${slug}`, fetcher)
const {data} = useSWR<ViewsType>(`/api/views/${slug}`, fetcher, {
revalidateOnFocus: false,
revalidateOnMount: true
})
const views = Number(data?.views)
useEffect(() => {
@ -21,7 +27,7 @@ export function Views({as: Component = 'span', slug}: { as?: ElementType, slug:
return (
<Component>
{` · ${views > 0 ? numberFormat(views) : '---'} views`}
{` · ${views > 0 ? numberFormat(views) : ''} views`}
</Component>
)
}