Added analytics to home page

This commit is contained in:
r-freeman 2023-04-11 17:48:47 +01:00
parent 126b66ac09
commit abd626a646
3 changed files with 18 additions and 4 deletions

View File

@ -9,9 +9,12 @@ type ViewsProps = {
slug: string
className?: string
shouldUpdateViews?: boolean
shouldRender?: boolean
}
export function Views({as: Component = 'span', slug, className, shouldUpdateViews = false}: ViewsProps) {
const isProd = process.env.NODE_ENV === 'production'
export function Views({as: Component = 'span', slug, className, shouldUpdateViews = true, shouldRender = true}: ViewsProps) {
const {data} = useSWR(`/api/views/${slug}`, fetcher) as { data: { views: number } }
const {mutate} = useSWRConfig()
@ -37,7 +40,7 @@ export function Views({as: Component = 'span', slug, className, shouldUpdateView
}, [])
useEffect(() => {
if (shouldUpdateViews) {
if (shouldUpdateViews && isProd) {
const registerView = async () => {
await fetcher(`/api/views/${slug}`,
{
@ -50,6 +53,8 @@ export function Views({as: Component = 'span', slug, className, shouldUpdateView
}
}, [])
if (!shouldRender) return null
return (
<Component className={className}>
{` · ${data?.views > 0 ? numberFormat(data.views) : '—'} views`}

View File

@ -28,7 +28,11 @@ function Article(article: Article) {
<Card.Eyebrow as="time" dateTime={article.date} decorate={false}>
{formatDate(article.date)}
</Card.Eyebrow>
<Views slug={article.slug} className="text-sm text-zinc-500 dark:text-zinc-400"/>
<Views
slug={article.slug}
className="text-sm text-zinc-500 dark:text-zinc-400"
shouldUpdateViews={false}
/>
</p>
</Card>
</article>
@ -134,6 +138,7 @@ export default function Home({articles}: { articles: Article[] }) {
<Resume/>
</div>
</div>
<Views slug='home' shouldRender={false}/>
</Container>
</>
)

View File

@ -19,7 +19,11 @@ function Article({article}: { article: Article }) {
<Card.Eyebrow as="time" dateTime={article.date} decorate={false}>
{formatDate(article.date)}
</Card.Eyebrow>
<Views slug={article.slug} className="text-sm text-zinc-500 dark:text-zinc-400"/>
<Views
slug={article.slug}
className="text-sm text-zinc-500 dark:text-zinc-400"
shouldUpdateViews={false}
/>
</p>
</Card>
</article>