rc-hooks
Version:
React Hooks Library.
66 lines (65 loc) • 2.37 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearCacheState = clearCacheState;
var tslib_1 = require("tslib");
var react_1 = require("react");
var ut2_1 = require("ut2");
var cache2_1 = require("cache2");
var config_1 = require("../utils/config");
var cacheNamespace = config_1.pkgName + '_useCacheState';
/**
* 获取 `useCacheState` 缓存实例。
*
* @see {@link https://github.com/caijf/cache2 | cache2}
* @param storage 自定义数据存储器,支持 `localStorage` `sessionStorage`。默认使用内存缓存。
* @returns 缓存实例。
*/
function getCache(storage) {
return new cache2_1.Cache(cacheNamespace, {
storage: storage
});
}
/**
* 清理 `useCacheState` 缓存。如果不传 `key`,表示清理全部。
*
* @see {@link https://github.com/caijf/cache2 | cache2}
* @param storage 自定义数据存储器,支持 `localStorage` `sessionStorage`。默认使用内存缓存。
* @param key 键名称。
*/
function clearCacheState(storage, key) {
var cache = getCache(storage);
if (key) {
cache.del(key);
}
else {
cache.clear();
}
}
/**
* 缓存状态。
*
* @param key 键名称。
* @param defaultValue 默认值。
* @param options 选项。
* @param options.ttl 过期时间,单位毫秒。默认不过期。
* @param options.storage 自定义数据存储器,支持 `localStorage` `sessionStorage`。默认使用内存缓存。
* @returns 状态值和更新状态值的函数。
*/
function useCacheState(key, defaultValue, options) {
if (options === void 0) { options = {}; }
var ttl = options.ttl, storage = options.storage;
var cache = (0, react_1.useMemo)(function () { return getCache(storage); }, [storage]);
var _a = tslib_1.__read((0, react_1.useState)(function () {
var cachedValue = cache.get(key);
return (0, ut2_1.isUndefined)(cachedValue) ? defaultValue : cachedValue;
}), 2), state = _a[0], setState = _a[1];
var set = (0, react_1.useCallback)(function (nextState) {
setState(function (prevState) {
var newState = nextState instanceof Function ? nextState(prevState) : nextState;
cache.set(key, newState, ttl);
return newState;
});
}, [cache, key, ttl]);
return [state, set];
}
exports.default = useCacheState;