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,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { getJSON } from "../../../api";
import { getJSON, itemsOrEmpty, readJSONCache } from "../../../api";
import { langQuery, type Lang } from "../../../i18n";
import { sourceLanguageQuery } from "../../../i18nLanguages";
import { MOCK_POSTS } from "../../../mocks/mockPosts";
@@ -114,6 +114,8 @@ export function usePostStream(params: PostStreamParams): PostStreamResult {
setError(null);
const myReq = ++reqIdRef.current;
let showedCached = false;
try {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, MOCK_DELAY_MS));
@@ -133,9 +135,26 @@ export function usePostStream(params: PostStreamParams): PostStreamResult {
params,
resetting ? undefined : cursorRef.current,
);
if (resetting) {
const cachedPage = readJSONCache<PostListResponse>(url);
if (cachedPage && myReq === reqIdRef.current) {
showedCached = true;
const cachedItems = itemsOrEmpty(cachedPage.items);
setItems(cachedItems);
cursorRef.current = cachedPage.nextCursor;
const cachedMore = !!cachedPage.nextCursor;
setHasMore(cachedMore);
hasMoreRef.current = cachedMore;
}
}
const res = await getJSON<PostListResponse>(url);
if (myReq !== reqIdRef.current) return;
setItems((prev) => (resetting ? res.items : [...prev, ...res.items]));
const freshItems = itemsOrEmpty(res.items);
setItems((prev) =>
resetting ? freshItems : [...prev, ...freshItems],
);
cursorRef.current = res.nextCursor;
const more = !!res.nextCursor;
setHasMore(more);
@@ -143,7 +162,7 @@ export function usePostStream(params: PostStreamParams): PostStreamResult {
}
} catch (e) {
if (myReq !== reqIdRef.current) return;
setError(String(e));
if (!showedCached) setError(String(e));
} finally {
if (myReq === reqIdRef.current) setIsLoading(false);
loadingRef.current = false;