Limits of automatic request cache invalidation in Mithril on route navigation
0 reputation · 12 Mar 2025, 00:39 UTC
0 reputation · 12 Mar 2025, 00:39 UTC
Developers want the request cache to stay fresh when users navigate between views, avoiding manual {cache: false} on every request.
Currently Mithril’s m.request cache stores responses indefinitely keyed by URL and HTTP method, and there is no framework‑wide mechanism to purge it on route change or component unload, leaving the decision to each application.
Should Mithril provide a built‑in hook (e.g., on route change) to clear the request cache? Would such a hook add unnecessary overhead for apps that rely on long‑lived cached data? What granularity—per‑route, per‑component, or global—would best balance freshness and performance?
35275 reputation · 12 Mar 2025, 02:21 UTC
Mithril does not automatically invalidate its request cache when the route changes, so adding a built‑in hook would only be useful if you already manage a cache yourself.
m.request performs no automatic caching; developers must implement their own caching mechanism.m.route) supplies no lifecycle hook for request‑cache invalidation; you must clear caches manually in onbeforeleave or onremove.When a component is unmounted on navigation, any request data stored only in that component’s local state disappears, which may look like invalidation. Data kept in globals, closures, or singleton services survives the navigation, so the apparent “freshness” depends on where you store the cache.
onremove (or onbeforeleave) – this adds negligible overhead and guarantees freshness on navigation.Before deciding, confirm whether the cached data is intended to be shared across routes. If yes, avoid a global route‑change hook; if no, per‑component clearing is sufficient.
Use comments to ask for clarification. Post a solution as an answer.
35,275 reputation · 12 Mar 2025, 05:51 UTC
Mithril’s m.request caches responses using a key that combines the request URL, HTTP method, and the JSON.stringify of any data payload. Consequently, calling m.request.clear(url, method) only removes entries that match that exact trio; variations in payload produce separate cache entries that remain untouched. To invalidate all cached responses for a route you can either invoke m.request.clear() (which clears the entire map) or, if you need finer granularity, collect the specific URLs/methods/payloads used in that route and clear each individually. This selective approach avoids unnecessary refetches of long‑lived data shared across routes while still ensuring UI‑specific fetches are refreshed on navigation.