Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/components/os/apps/BlogApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,46 @@ type BlogPayload = {
fetchedAt: string;
};

// Module-level cache to prevent duplicate fetches when multiple components
// mount simultaneously and use this hook, or when the window is opened/closed frequently.
let fetchPromise: Promise<BlogPayload> | null = null;
let cachedPayload: BlogPayload | null = null;

const dateFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
});

export default function BlogApp() {
const [payload, setPayload] = useState<BlogPayload | null>(null);
const [payload, setPayload] = useState<BlogPayload | null>(cachedPayload);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');

useEffect(() => {
let cancelled = false;
fetch('/api/blog.json')
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))

if (cachedPayload) {
setPayload(cachedPayload);
return;
}

if (!fetchPromise) {
// Security: use an AbortSignal timeout to prevent application hangs
fetchPromise = fetch('/api/blog.json', { signal: AbortSignal.timeout(10000) })
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))));
}

fetchPromise
.then((data: BlogPayload) => {
cachedPayload = data;
if (!cancelled) setPayload(data);
})
.catch((err) => {
fetchPromise = null; // Allow retry on error
if (!cancelled) setError(err instanceof Error ? err.message : 'failed to load');
});

return () => {
cancelled = true;
};
Expand Down
Loading