refactor: Refactor Feed story fetching for improved network resilience

Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
This commit is contained in:
2025-11-19 17:46:30 +00:00
parent 83cb6fc0ae
commit 55bf75742e

View File

@@ -12,32 +12,53 @@ function Feed({ updateCache }) {
fetch('/api') fetch('/api')
.then(res => res.json()) .then(res => res.json())
.then( .then(
(result) => { async (result) => {
const updated = !stories || stories[0].id !== result.stories[0].id; const newApiStories = result.stories;
const updated = !stories || !stories.length || stories[0].id !== newApiStories[0].id;
console.log('New stories available:', updated); console.log('New stories available:', updated);
if (!updated) return; if (!updated) return;
//setStories(result.stories); const existingStoryIds = new Set(stories ? stories.map(s => s.id) : []);
//localStorage.setItem('stories', JSON.stringify(result.stories));
//localForage.clear(); for (const newStory of [...newApiStories].reverse()) {
//result.stories.forEach((x, i) => { if (existingStoryIds.has(newStory.id)) {
// fetch('/api/' + x.id) continue;
// .then(res => res.json()) }
// .then(result => {
// localForage.setItem(x.id, result.story) try {
// .then(console.log('preloaded', x.id, x.title)); const storyRes = await fetch('/api/' + newStory.id);
// updateCache(x.id, result.story); if (!storyRes.ok) throw new Error('Story fetch failed');
// }, error => {} const storyResult = await storyRes.json();
// ); const fullStory = storyResult.story;
//});
await localForage.setItem(fullStory.id, fullStory);
console.log('preloaded', fullStory.id, fullStory.title);
updateCache(fullStory.id, fullStory);
setStories(prevStories => {
const currentStories = Array.isArray(prevStories) ? prevStories : [];
const updatedStories = [newStory, ...currentStories];
const poppedStory = updatedStories.pop();
if (poppedStory) {
localForage.removeItem(poppedStory.id);
}
localStorage.setItem('stories', JSON.stringify(updatedStories));
return updatedStories;
});
} catch (error) {
console.log('Skipping story due to fetch error', newStory.id, error);
}
}
}, },
(error) => { (error) => {
setError(true); setError(true);
} }
); );
}, [updateCache]); }, [updateCache, stories]);
return ( return (
<div className='container'> <div className='container'>