Added article views to homepage

This commit is contained in:
r-freeman 2023-01-26 23:29:39 +00:00
parent 819826422b
commit bf8c522ef0
3 changed files with 19 additions and 6 deletions

View File

@ -7,9 +7,16 @@ type ViewsType = {
views: string
}
type ViewsProps = {
as?: ElementType
slug: string
className?: string
shouldUpdateViews?: boolean
}
const updateViews = (slug: string) => fetcher(`/api/views/${slug}`, {method: 'POST'})
export function Views({as: Component = 'span', slug}: { as?: ElementType, slug: string }) {
export function Views({as: Component = 'span', slug, className, shouldUpdateViews = true}: ViewsProps) {
const {data} = useSWR<ViewsType>(`/api/views/${slug}`, fetcher, {
revalidateOnFocus: false,
revalidateOnMount: true
@ -17,11 +24,13 @@ export function Views({as: Component = 'span', slug}: { as?: ElementType, slug:
const views = Number(data?.views)
useEffect(() => {
updateViews(slug).then(r => r)
if (shouldUpdateViews) {
updateViews(slug).then(r => r);
}
}, [slug])
return (
<Component>
<Component className={className}>
{` · ${views > 0 ? numberFormat(views) : '—'} views`}
</Component>
)

View File

@ -10,6 +10,7 @@ import {
TwitterIcon
} from '@/components/SocialIcons'
import {SocialLink} from '@/components/SocialLink'
import {Views} from '@/components/Views'
import {formatDate} from '@/lib/formatDate'
import {generateRssFeed} from '@/lib/generateRssFeed'
import {generateSitemap} from '@/lib/generateSitemap'
@ -71,9 +72,12 @@ function Article(article: Article) {
<Card.Title href={`/writing/${article.slug}`}>
{article.title}
</Card.Title>
<p className="flex order-first space-x-1 z-10">
<Card.Eyebrow as="time" dateTime={article.date} decorate={false}>
{formatDate(article.date)}
</Card.Eyebrow>
<Views slug={article.slug} shouldUpdateViews={false} className="text-sm text-zinc-500 dark:text-zinc-400"/>
</p>
<Card.Description>{article.description}</Card.Description>
<Card.Cta>Read more</Card.Cta>
</Card>