Add stale cache for public data

This commit is contained in:
TerryM
2026-05-28 23:09:18 +08:00
parent 5ae9647465
commit 320739f91b
8 changed files with 263 additions and 83 deletions

View File

@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from "react";
import { useParams } from "react-router-dom";
import { getJSON, itemsOrEmpty, type Category } from "../../api";
import { getJSON, itemsOrEmpty, readJSONCache, type Category } from "../../api";
import { AssetStreamPage } from "../../components/AssetStreamPage";
import { langQuery, useI18n } from "../../i18n";
import { cleanCategoryDisplayName } from "../../utils/categoryDisplay";
@@ -13,18 +13,32 @@ export function CategoryPage() {
useEffect(() => {
if (!slug) return;
setTitle(slug);
getJSON<Category[]>(
`/api/categories?lang=${encodeURIComponent(langQuery(lang))}`,
)
.then((cats) =>
setTitle(
cleanCategoryDisplayName(
itemsOrEmpty(cats).find((x) => x.slug === slug)?.name ?? slug,
),
let cancelled = false;
const categoriesUrl = `/api/categories?lang=${encodeURIComponent(
langQuery(lang),
)}`;
const applyTitle = (cats: Category[]) =>
setTitle(
cleanCategoryDisplayName(
itemsOrEmpty(cats).find((x) => x.slug === slug)?.name ?? slug,
),
)
.catch(() => setTitle(slug));
);
setTitle(slug);
const cachedCategories = readJSONCache<Category[]>(categoriesUrl);
if (cachedCategories) applyTitle(cachedCategories);
getJSON<Category[]>(categoriesUrl)
.then((cats) => {
if (!cancelled) applyTitle(cats);
})
.catch(() => {
if (!cancelled && !cachedCategories) setTitle(slug);
});
return () => {
cancelled = true;
};
}, [slug, lang]);
return <AssetStreamPage title={title || slug} scope={scope} />;