Add stale cache for public data
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { Info, Search as SearchIcon, X } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { getJSON, itemsOrEmpty } from "../api";
|
||||
import { getJSON, itemsOrEmpty, readJSONCache } from "../api";
|
||||
import { langQuery, type Lang } from "../i18n";
|
||||
import type { Post, PostListResponse } from "../types/post";
|
||||
import { MessageBubble } from "./messageStream/MessageBubble";
|
||||
@@ -75,20 +75,22 @@ export function SearchPanel({
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const tagsUrl = buildPostsUrl({
|
||||
lang: langParam,
|
||||
sort: "latest",
|
||||
limit: TAG_SOURCE_LIMIT,
|
||||
});
|
||||
const cachedTags = readJSONCache<PostListResponse>(tagsUrl);
|
||||
if (cachedTags) setTags(extractTags(itemsOrEmpty(cachedTags.items)));
|
||||
|
||||
setIsTagLoading(true);
|
||||
getJSON<PostListResponse>(
|
||||
buildPostsUrl({
|
||||
lang: langParam,
|
||||
sort: "latest",
|
||||
limit: TAG_SOURCE_LIMIT,
|
||||
}),
|
||||
)
|
||||
getJSON<PostListResponse>(tagsUrl)
|
||||
.then((res) => {
|
||||
if (cancelled) return;
|
||||
setTags(extractTags(itemsOrEmpty(res.items)));
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setTags([]);
|
||||
if (!cancelled && !cachedTags) setTags([]);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setIsTagLoading(false);
|
||||
@@ -102,17 +104,31 @@ export function SearchPanel({
|
||||
const showTagPosts = (tag: string) => {
|
||||
setSelectedTag(tag);
|
||||
onQueryChange(tag);
|
||||
const searchUrl = buildSearchUrl({
|
||||
lang: langParam,
|
||||
q: tag,
|
||||
limit: TAG_RESULT_LIMIT,
|
||||
});
|
||||
const cachedPosts = readJSONCache<PostListResponse>(searchUrl);
|
||||
if (cachedPosts) {
|
||||
setTagPosts(
|
||||
itemsOrEmpty(cachedPosts.items).filter((post) =>
|
||||
post.tags?.some((postTag) => postTag.trim() === tag),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
setIsPostLoading(true);
|
||||
getJSON<PostListResponse>(
|
||||
buildSearchUrl({ lang: langParam, q: tag, limit: TAG_RESULT_LIMIT }),
|
||||
)
|
||||
getJSON<PostListResponse>(searchUrl)
|
||||
.then((res) => {
|
||||
const exactMatches = itemsOrEmpty(res.items).filter((post) =>
|
||||
post.tags?.some((postTag) => postTag.trim() === tag),
|
||||
);
|
||||
setTagPosts(exactMatches);
|
||||
})
|
||||
.catch(() => setTagPosts([]))
|
||||
.catch(() => {
|
||||
if (!cachedPosts) setTagPosts([]);
|
||||
})
|
||||
.finally(() => setIsPostLoading(false));
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user