wrap hit counter with an error boundary in case the API falls on its face again

This commit is contained in:
2024-01-21 13:22:14 -05:00
parent dbebd35c4d
commit 5b0c126ffc
5 changed files with 284 additions and 300 deletions
+5 -1
View File
@@ -1,4 +1,5 @@
import useSWRImmutable from "swr/immutable";
import { useErrorBoundary } from "react-error-boundary";
import commaNumber from "comma-number";
import Loading from "../Loading";
import fetcher from "../../lib/helpers/fetcher";
@@ -9,6 +10,8 @@ export type HitCounterProps = {
};
const HitCounter = ({ slug }: HitCounterProps) => {
const { showBoundary } = useErrorBoundary();
// use immutable SWR to avoid double (or more) counting views:
// https://swr.vercel.app/docs/revalidation#disable-automatic-revalidations
const { data, error } = useSWRImmutable<PageStats>(
@@ -18,8 +21,9 @@ const HitCounter = ({ slug }: HitCounterProps) => {
fetcher
);
// fail secretly
// fail somewhat silently, see error boundary in NoteMeta component
if (error) {
showBoundary(`${error}`);
return null;
}
+6 -2
View File
@@ -1,3 +1,4 @@
import { ErrorBoundary } from "react-error-boundary";
import Link from "../Link";
import Time from "../Time";
import HitCounter from "../HitCounter";
@@ -106,8 +107,11 @@ const NoteMeta = ({ slug, date, title, htmlTitle, tags }: NoteMetaProps) => {
marginRight: 0,
}}
>
<Icon as={FiEye} />
<HitCounter slug={`notes/${slug}`} />
{/* completely hide this block if anything goes wrong on the backend */}
<ErrorBoundary fallback={null}>
<Icon as={FiEye} />
<HitCounter slug={`notes/${slug}`} />
</ErrorBoundary>
</MetaItem>
)}
</Wrapper>