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

View File

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