0

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?

asked Apr 28, 2022 at 12:19
3
  • 1
    Not 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. Commented 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 :-( Commented 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. Commented Aug 29, 2024 at 16:05

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.