Goal
We have an app with different articles. I want to cache an article when the user has read it, but make sure that I display the latest data. I came up with this hook:
React.useEffect(() => {
(async function fetchArticle() {
const articleURL = `${BASE_URL}/services/node/${route.params.nid}`;
try {
setLoading(true);
const cached = await articleCache.get(route.params.nid);
if (cached) {
setArticle(JSON.parse(cached));
axios(articleURL).then(({ data }) =>
articleCache.set(route.params.nid, JSON.stringify(data)),
);
} else {
const { data } = await axios(articleURL);
await articleCache.set(route.params.nid, JSON.stringify(data));
setArticle(data);
}
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
}, [route.params.nid]);
Does it make sense to fetch the data again every time? It seems kind of excessive to me, but I can't think of another away without the API being changed and returning some kind of timestamp instead of the full article to reduce the size of the request.
Is this way ok or can it be improved?
-
1Not an answer but an observation: there's a whole layer in the browser that's designed to handle caching requests, including things like if-modified-since so that data does not have to be unnecessarily re-sent, and it's a shame that modern SPA style erases all of that.pjc50– pjc502022年04月28日 12:29:38 +00:00Commented Apr 28, 2022 at 12:29
-
Well it's a mobile app. I am not sure that applies. But yeah, I am always wondering whether caching works with something like React, and the answer seems to be no :-(Gh05d– Gh05d2022年04月28日 12:37:17 +00:00Commented Apr 28, 2022 at 12:37
-
Well, the improvement is not re-computing the cache every time. This is the hard part and requires you to insert an if-statement to assert if the cached result is too old. Upon caching you could add a property to each article object with a timestamp now and when you pull things out from it you would check if timestamp > 1hour or some convenient period of time before re-fetching over network.htor– htor2024年08月29日 16:05:10 +00:00Commented Aug 29, 2024 at 16:05