Add stale cache for public data
This commit is contained in:
@@ -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} />;
|
||||
|
||||
Reference in New Issue
Block a user