staleCache()
Show previous results while refreshing.
Try the example
Load the project summary twice within two seconds. The second read uses the cache. Wait longer and load again: the previous version appears while a fresh one is requested.
Cache is empty.
Ready to load.
Add it to your project
- Copy the HTML. Place the markup inside the component where this behavior belongs. The preview’s visual classes are website styles; use your own design system.
- Connect the behavior. Copy the JavaScript tab and call its exported
mount(element)after your component’s elements exist. Replace simulated delays and data operations with your own application code. - Clean up. Call the returned cleanup when the component unmounts. It aborts the example’s listeners and releases the helper’s timers, observers or state.
API and lifecycle
Create a cache for non-sensitive reads. read(key, fetcher, onValue) delivers cached data first, then refreshes stale data. Concurrent reads for the same key share pending work. Defaults: 30-second TTL, 50 entries.
- Interface
ttl, max; read/clear- Lifecycle
- clear() empties the cache and invalidates pending delivery into the old cache generation. Scope the instance to one user/session and clear on logout. Data is not persisted to disk.
Accessibility and safety
Implementation notes
Use only non-sensitive reads, scope to user/session, and clear on logout.
The fetcher must reject on HTTP errors. Distinguish stale data from a fresh response where that affects a decision, and avoid caching sensitive results.
What to check
Load within the TTL, then after it expires. Verify cached data can appear before the refresh, failures are handled, and clearing prevents old results leaking into a new session.