UNPKG

@excentone/spfx-react

Version:

Contains custom ReactJs components and hooks intended to use when developing SharePoint Framework (SPFx) Web components.

60 lines (58 loc) 2.43 kB
import { DateTime } from "luxon"; import { usePnpSessionStorage } from "../usePnpClientStorage"; import { useCallback, useEffect, useMemo, useState } from "react"; import { isEqual } from "@microsoft/sp-lodash-subset"; import { isFunction } from "@excentone/spfx-utilities"; /** * `useCachedListQuery` is a custom hook to easily use and cache an object to be used to filter a list of records. * @param cacheKey The unique key of the cache. * @param options The options to pass through the hook. * @returns A tuple that contains the state of the filters and operations to modify it. */ export const useCachedListQuery = (cacheKey, options) => { const defaultOptions = useMemo(() => ({ enableCaching: true, initialValues: {}, autoCacheOnChange: false, cacheExpiration: DateTime.now().plus({ 'day': 1 }).toJSDate() }), []); const { enableCaching, initialValues, cacheExpiration, autoCacheOnChange } = useMemo(() => ({ ...defaultOptions, ...options }), [options]); const [cached, { setState: setCachedValues, resetState: resetCachedValues, getOrInitState: getCachedValues }] = usePnpSessionStorage(cacheKey, initialValues, cacheExpiration); const [values, setValues] = useState(cached); const cacheValues = useCallback(() => setCachedValues(values), [setCachedValues, values]); const resetValues = useCallback(() => { setValues(initialValues); resetCachedValues(); }, [resetCachedValues, setValues, initialValues]); const setField = useCallback((fieldName, setValue) => setValues(prev => { const next = Object.assign({}, prev); next[fieldName] = isFunction(setValue) ? setValue(next[fieldName]) : setValue; return next; }), [setValues]); const getInitialValues = useCallback(() => initialValues, [initialValues]); useEffect(() => { if (enableCaching && autoCacheOnChange && !isEqual(values, cached)) cacheValues(); }, [autoCacheOnChange, values]); useEffect(() => { if (enableCaching && cached && !isEqual(values, cached)) setValues(cached); }, [cached]); return [ values, { setField, setValues, resetValues, cacheValues, getCachedValues, getInitialValues, } ]; }; //# sourceMappingURL=useCachedListQuery.js.map