1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-07-21 06:41:17 -04:00

add page stats typings

This commit is contained in:
2022-06-30 09:17:12 -04:00
parent ae2cb50cbe
commit 7da0a713a4
9 changed files with 80 additions and 87 deletions

View File

@@ -1,42 +1,36 @@
import useSWR from "swr";
import useSWRImmutable from "swr/immutable";
import commaNumber from "comma-number";
import Loading from "../Loading";
import fetcher from "../../lib/helpers/fetcher";
import type { PageStats } from "../../types";
export type HitCounterProps = {
slug: string;
className?: string;
};
const HitCounter = ({ slug, className }: HitCounterProps) => {
// start fetching repos from API immediately
const { data, error } = useSWR(
const HitCounter = ({ slug }: HitCounterProps) => {
// use immutable SWR to avoid double (or more) counting views:
// https://swr.vercel.app/docs/revalidation#disable-automatic-revalidations
const { data, error } = useSWRImmutable<PageStats>(
`/api/hits/?${new URLSearchParams({
slug,
})}`,
fetcher,
{
// avoid double (or more) counting views
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
fetcher
);
// show spinning loading indicator if data isn't fetched yet
if (!data) {
return <Loading boxes={3} width={20} />;
}
// fail secretly
if (error) {
return null;
}
// show spinning loading indicator if data isn't fetched yet
if (!data) {
return <Loading boxes={3} width={20} />;
}
// we have data!
return (
<span title={`${commaNumber(data.hits)} ${data.hits === 1 ? "view" : "views"}`} className={className}>
{commaNumber(data.hits)}
</span>
<span title={`${commaNumber(data.hits)} ${data.hits === 1 ? "view" : "views"}`}>{commaNumber(data.hits)}</span>
);
};