cache-async-fn
v0.1.0
Published
Cache asynchronous functions where they should be
Downloads
1
Readme
cache-async-fn
Usage
Initialization
With MobX:
import { observable } from 'mobx';
import { cacheAsyncFactory } from 'cache-async-fn';
function createCache<T>(): { value: Record<string, T> } {
return observable(
{ value: {} },
{
value: observable.ref,
},
);
}
const { cacheAsync } = cacheAsyncFactory(createCache);
With Vue:
import { ref } from 'vue';
import { cacheAsyncFactory } from 'cache-async-fn';
function createCache<T>(): { value: Record<string, T> } {
return ref();
}
const { cacheAsync } = cacheAsyncFactory(createCache);
Cache APIs
const myApi = cacheAsync(myApiCall, {
resolver: (params) => [groupKey, cacheKey],
});
// Call from anywhere
async function someAction() {
const response = await myApi(params);
}
// Get the current value anytime
function getValueSync() {
return myApi.get(params);
}
Each groupKey
has its own cache. The cache is invalidated when the cacheKey
changes.
Use Cases
Load once globally
The is the default behavior.
const loadOnceGlobally = cacheAsync(api);
// or
const loadOnceGlobally = cacheAsync(api, {
resolver: () => '',
});
Load on param change
const loadOnParamChange = cacheAsync(api, {
resolver: (params) => ['', JSON.stringify(params)],
});
Cache data for multiple tabs
The data for each tab will be cached in a different group, with the parameters as its cache key.
const loadOnParamChange = cacheAsync(api, {
resolver: (params) => [params.tab, JSON.stringify(params)],
});