From abd626a646e9bf3089d5cfce42a900038dc18914 Mon Sep 17 00:00:00 2001
From: r-freeman
Date: Tue, 11 Apr 2023 17:48:47 +0100
Subject: [PATCH] Added analytics to home page
---
components/ui/Views.tsx | 9 +++++++--
pages/index.tsx | 7 ++++++-
pages/writing/index.tsx | 6 +++++-
3 files changed, 18 insertions(+), 4 deletions(-)
diff --git a/components/ui/Views.tsx b/components/ui/Views.tsx
index 0361bba..d263af9 100644
--- a/components/ui/Views.tsx
+++ b/components/ui/Views.tsx
@@ -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 (
{` · ${data?.views > 0 ? numberFormat(data.views) : '—'} views`}
diff --git a/pages/index.tsx b/pages/index.tsx
index 9965920..63bc19d 100644
--- a/pages/index.tsx
+++ b/pages/index.tsx
@@ -28,7 +28,11 @@ function Article(article: Article) {
{formatDate(article.date)}
-
+
@@ -134,6 +138,7 @@ export default function Home({articles}: { articles: Article[] }) {
+
>
)
diff --git a/pages/writing/index.tsx b/pages/writing/index.tsx
index 1a59ce8..d6ab654 100644
--- a/pages/writing/index.tsx
+++ b/pages/writing/index.tsx
@@ -19,7 +19,11 @@ function Article({article}: { article: Article }) {
{formatDate(article.date)}
-
+