@excentone/spfx-react
Version:
Contains custom ReactJs components and hooks intended to use when developing SharePoint Framework (SPFx) Web components.
46 lines (44 loc) • 2.47 kB
JavaScript
import { useBoolean } from "@fluentui/react-hooks";
import { isEqual } from "@microsoft/sp-lodash-subset";
import { PnPClientStorage } from "@pnp/common";
import { DateTime } from "luxon";
import { useMemo, useState, useEffect, useCallback, } from "react";
const usePnpClientStorage = (cacheKey, storageName, initialState, selectStore, expire) => {
const [state, setState] = useState(initialState);
const [initializing, { setFalse: initializationDone }] = useBoolean(true);
const storage = useMemo(() => selectStore(new PnPClientStorage()), [selectStore]);
const expiration = useMemo(() => {
if (!expire) {
expire = DateTime.now().plus({ 'hours': 12 }).toJSDate();
const dt = DateTime.fromJSDate(expire);
console.warn(`[${cacheKey}]: No expiration date set, will use the default expiration. Cached data will expire ${dt.diffNow('hours')}: ${dt.toFormat('YYYY-MM-DD HH:mm')}`);
}
return expire;
}, [expire]);
const resetState = useCallback(() => setState({ ...initialState }), [initialState]);
const getOrInitState = useCallback(() => storage.getOrPut(cacheKey, () => Promise.resolve(initialState), expiration), [storage, cacheKey, initialState, expiration]);
useEffect(() => {
storage.deleteExpired();
if (initializing && cacheKey) {
if (!storage.enabled) {
console.info(`[${cacheKey}]: "${storageName}" storage is disabled. Persisting search parameters will not work.`);
return;
}
console.info(`[${cacheKey}]: Initial State: `, initialState);
getOrInitState()
.then(setState)
.finally(initializationDone);
}
}, [cacheKey, initialState]);
useEffect(() => {
if (!initializing && state) {
const cachedState = storage.get(cacheKey);
if (cachedState !== state || !isEqual(cachedState, state))
storage.put(cacheKey, state, expiration);
}
}, [cacheKey, state]);
return [state, { setState, resetState, getOrInitState }];
};
export const usePnpLocalStorage = (key, initialValue, expire) => usePnpClientStorage(key, 'local', initialValue, storage => storage.local, expire);
export const usePnpSessionStorage = (key, initialValue, expire) => usePnpClientStorage(key, 'session', initialValue, storage => storage.session, expire);
//# sourceMappingURL=usePnpClientStorage.js.map