-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Update ViewCounter component to use Redis
- Loading branch information
1 parent
30f618a
commit f8419e8
Showing
1 changed file
with
8 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<Views>(`/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<number>(`pageviews:${slug}`)) || 0; | ||
|
||
return <div>{viewCount} views</div>; | ||
return <p className="text-sm text-neutral-400">{views} views</p>; | ||
}; | ||
|
||
export default ViewCounter; |