From f8419e8586ea90f59ae13e4ef757f2ed19fd0721 Mon Sep 17 00:00:00 2001 From: Ru Chern Chong Date: Fri, 1 Nov 2024 00:23:24 +0800 Subject: [PATCH] feat: Update ViewCounter component to use Redis --- components/ViewCounter.tsx | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/components/ViewCounter.tsx b/components/ViewCounter.tsx index 15319cb..9ed9108 100644 --- a/components/ViewCounter.tsx +++ b/components/ViewCounter.tsx @@ -1,25 +1,19 @@ -"use client"; -import { useEffect } from "react"; -import useSWR from "swr"; -import type { Views } from "@prisma/client"; +import { Redis } from "@upstash/redis"; -interface ViewCounterProps { +interface Props { slug: string; } -const fetcher = (...args: [RequestInfo, RequestInit?]) => - fetch(...args).then((res) => res.json()); +const redis = Redis.fromEnv(); -const ViewCounter = ({ slug }: ViewCounterProps) => { - const { data } = useSWR(`/api/views/${slug}`, fetcher); +const view = async (slug: string) => await redis.incr(`pageviews:${slug}`); - useEffect(() => { - fetch(`/api/views/${slug}`, { method: "POST" }); - }, [slug]); +const ViewCounter = async ({ slug }: Props) => { + await view(slug); - const viewCount = data?.count || 0; + const views = (await redis.get(`pageviews:${slug}`)) || 0; - return
{viewCount} views
; + return

{views} views

; }; export default ViewCounter;