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?