UNPKG

@connected/react

Version:

The hassle free way to call your server-side code

37 lines 1.36 kB
import React, { useCallback, useRef } from 'react'; import Lru from './lru.js'; import ConnectedContext from './connected-context.js'; function prepareInitialData(initialData, ttl) { if (!initialData) { return undefined; } const t = new Date(); t.setMilliseconds(t.getMilliseconds() + ttl); const result = {}; const keys = Object.keys(initialData); keys.forEach((key) => { result[key] = { ttl: t, data: initialData[key], }; }); return result; } function ConnectedProvider({ maxCacheSize = 500, dataTtl = 60 * 1000, errorTtl = 5 * 1000, factory = (klass, ...args) => new klass(args), initialCacheData = {}, onCacheUpdate, children, }) { const handleCacheUpdate = useCallback((action, key, value) => { if (onCacheUpdate && action === 'set' && 'data' in value) { onCacheUpdate(key, value.data); } }, [onCacheUpdate]); const { current: cache } = useRef(new Lru(prepareInitialData(initialCacheData, dataTtl), maxCacheSize, handleCacheUpdate)); return React.createElement(ConnectedContext.Provider, { value: { cache, dataTtl: dataTtl, errorTtl: errorTtl, factory: factory, }, }, children); } export default ConnectedProvider; //# sourceMappingURL=connected-provider.js.map