remember-cache
v0.3.0
Published
Small browser cache helpers inspired by Laravel Cache::remember
Maintainers
Readme
remember-cache
Small browser cache helpers inspired by Laravel's Cache::remember().
remember-cache stores values in localStorage through localit. It is intended for browser apps and test environments that provide localStorage.
Installation
npm i remember-cacheAPI
import cache, { createCache } from "remember-cache";Basic storage
Use get, set, has, and forget when you want direct cache access.
cache.set("current-user", user, { seconds: 300 });
cache.get("current-user");
cache.get("current-user", null);
cache.has("current-user");
cache.forget("current-user");remember(key, seconds, handler, options?)
Returns the cached value for key when it exists. Otherwise, it resolves handler, stores the result, and returns it.
handler can be a plain value, a function, or a promise.
const user = await cache.remember("current-user", 60, async () => {
const response = await fetch("/api/me");
return response.json();
});Pass 0 as the lifetime to store the value without an expiration date.
refresh(key, handler, options?)
Ignores the previous cached value, resolves handler, stores the new value, notifies subscribers, and returns it.
await cache.refresh("current-user", fetchUser, { seconds: 300 });rememberMany(entries, seconds, options?)
Resolves several remember calls in parallel and returns an object with the same keys.
const data = await cache.rememberMany({
user: fetchUser,
settings: fetchSettings,
}, 60);autoUpdate(key, handler, options?)
Returns the previous cached value immediately when one exists, while updating the cache in the background.
If there is no cached value yet, it returns a promise for the current handler result.
const firstResult = await cache.autoUpdate("news", fetchNews);
const staleResult = cache.autoUpdate("news", fetchLatestNews);Use onUpdate and onError to connect the refresh to a reactive store, ref, signal, or state setter without depending on a specific framework.
const state = { value: null };
state.value = await cache.autoUpdate("news", fetchNews, {
staleTime: 30,
maxAge: 300,
onUpdate(value) {
state.value = value;
},
onError(error) {
console.error(error);
},
});staleTime skips the background refresh while the cached value is still fresh. maxAge sets the cache expiration. Both values are in seconds.
subscribe(key, callback, options?)
Subscribes to cache changes made through remember-cache methods. It returns an unsubscribe function.
const unsubscribe = cache.subscribe("news", value => {
console.log(value);
}, { family: "cache-autoupdate" });
unsubscribe();resource(key, handler, options?)
Creates a small framework-agnostic state object for UI code.
const user = cache.resource("current-user", fetchUser);
user.value;
user.loading;
user.error;
user.subscribe(resource => {
render(resource.value);
});
await user.refresh();autoClear(key, handler, options?)
Stores the value like remember, but keeps only the most recent entries in the cache-autoclear family.
cache.config.autoClearEntries = 20;
const page = await cache.autoClear("products-page-1", async () => {
const response = await fetch("/api/products?page=1");
return response.json();
});By default, autoClear keeps 10 entries and each entry expires after cache.config.autoClearMaxTime seconds.
Families
Most methods accept a custom family option. Families let you group entries and clear them together.
await cache.remember("profile", 60, fetchProfile, { family: "users" });
cache.clearFamily("users");The built-in cache families are:
cache-remembercache-autoupdatecache-autoclear
Custom cache instances
Use createCache when you want a different default family or storage.
const sessionCache = createCache({
family: "session",
storage: sessionStorage,
});
sessionCache.set("token-preview", preview);Helpers
cache.clearFamily("cache-remember");
cache.getFamilyKeys("cache-autoclear");
cache.getDomainExpirationDates("cache-autoclear");Notes
This package depends on localStorage by default, so server-side rendering environments need to call it only in the browser or provide a compatible storage implementation.
