@dr.pogodin/react-global-state 0.10.0-alpha.5 → 0.10.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["_useAsyncData","_interopRequireDefault","require","useAsyncCollection","id","path","loader","options","itemPath","useAsyncData","oldData","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>\n >,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,aAAA,GAAAC,sBAAA,CAAAC,OAAA;AAJA;AACA;AACA;;AAaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAyBA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EACrCC,OAA6B,GAAG,CAAC,CAAC,EACT;EACzB,MAAMC,QAAQ,GAAGH,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAO,IAAAK,qBAAY,EACjBD,QAAQ,EACPE,OAAqB,IAAKJ,MAAM,CAACF,EAAE,EAAEM,OAAO,CAAC,EAC9CH,OACF,CAAC;AACH;AAAC,IAAAI,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcV,kBAAkB"}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["_useAsyncData","_interopRequireDefault","require","useAsyncCollection","id","path","loader","options","itemPath","useAsyncData","oldData","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,aAAA,GAAAC,sBAAA,CAAAC,OAAA;AAJA;AACA;AACA;;AAaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AA0BA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EACrCC,OAA6B,GAAG,CAAC,CAAC,EACT;EACzB,MAAMC,QAAQ,GAAGH,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAO,IAAAK,qBAAY,EACjBD,QAAQ,EACPE,OAAqB,IAAKJ,MAAM,CAACF,EAAE,EAAEM,OAAO,CAAC,EAC9CH,OACF,CAAC;AACH;AAAC,IAAAI,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcV,kBAAkB"}
@@ -197,6 +197,7 @@ function useAsyncData(path, loader, options = {}) {
197
197
  return {
198
198
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
199
199
  loading: Boolean(localState.operationId),
200
+ reload: customLoader => load(path, customLoader || loader, globalState, null),
200
201
  timestamp: localState.timestamp
201
202
  };
202
203
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["_lodash","require","_react","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","MIN_MS","newAsyncDataEnvelope","initialData","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","isDebugMode","console","log","uuid","operationIdPath","set","get","state","groupCollapsed","cloneDeep","Date","now","groupEnd","useAsyncData","options","maxage","undefined","refreshAge","garbageCollectAge","getGlobalState","initialValue","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","useGlobalState","loading","Boolean","_default","exports","default"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState, null);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AAEA,IAAAG,QAAA,GAAAH,OAAA;AAEA,IAAAI,oBAAA,GAAAJ,OAAA;AACA,IAAAK,eAAA,GAAAC,sBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAbA;AACA;AACA;;AAsBA,MAAMQ,cAAc,GAAG,CAAC,GAAGC,eAAM,CAAC,CAAC;;AAY5B,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EACL;EAC3B,OAAO;IACLC,IAAI,EAAED,WAAW;IACjBE,OAAO,EAAE,CAAC;IACVC,WAAW,EAAE,EAAE;IACfC,SAAS,EAAE;EACb,CAAC;AACH;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;A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CAAC,CAAC,GAAGgB,MAAM,CAACrC,SAAS,KAC1C,CAACqC,MAAM,CAACtC,WAAW,IAAIsC,MAAM,CAACtC,WAAW,CAACwC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,EAAE;QAChEtC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAEiC,MAAM,CAACxC,IAAI,CAAC;QAC5CyC,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;;IAEF,MAAME,IAAI,GAAGhB,OAAO,CAACgB,IAAI,IAAI,EAAE;IAC/B,IAAAL,gBAAS,EAAC,MAAM;MAAE;MAChB,IAAI,CAACG,aAAa,IAAIE,IAAI,CAACC,MAAM,EAAExC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;IAC1E,CAAC,EAAEoC,IAAI,CAAC,CAAC,CAAC;EACZ;;EAEA,MAAM,CAACE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjCzC,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLE,IAAI,EAAE4B,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGqB,UAAU,CAAC1C,SAAS,GAAG,IAAI,GAAG0C,UAAU,CAAC7C,IAAI;IACzE+C,OAAO,EAAEC,OAAO,CAACH,UAAU,CAAC3C,WAAW,CAAC;IACxCC,SAAS,EAAE0C,UAAU,CAAC1C;EACxB,CAAC;AACH;AAAC,IAAA8C,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEczB,YAAY"}
1
+ {"version":3,"file":"useAsyncData.js","names":["_lodash","require","_react","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","MIN_MS","newAsyncDataEnvelope","initialData","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","isDebugMode","console","log","uuid","operationIdPath","set","get","state","groupCollapsed","cloneDeep","Date","now","groupEnd","useAsyncData","options","maxage","undefined","refreshAge","garbageCollectAge","getGlobalState","initialValue","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","useGlobalState","loading","Boolean","reload","customLoader","_default","exports","default"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState, null);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n\n reload: (customLoader?: AsyncDataLoaderT<DataT>) => load(\n path,\n customLoader || loader,\n globalState,\n null,\n ),\n\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AAEA,IAAAG,QAAA,GAAAH,OAAA;AAEA,IAAAI,oBAAA,GAAAJ,OAAA;AACA,IAAAK,eAAA,GAAAC,sBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAbA;AACA;AACA;;AAsBA,MAAMQ,cAAc,GAAG,CAAC,GAAGC,eAAM,CAAC,CAAC;;AAY5B,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EACL;EAC3B,OAAO;IACLC,IAAI,EAAED,WAAW;IACjBE,OAAO,EAAE,CAAC;IACVC,WAAW,EAAE,EAAE;IACfC,SAAS,EAAE;EACb,CAAC;AACH;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,IAAIA,CACjBC,IAA+B,EAC/BC,MAA+B,EAC/BC,WAAsD,EACtDC,OAAqB,EACrBC,UAAqB,GAAG,GAAG,EACZ;EACf,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,EAAC,CAAC,EAAE;IAC1D;IACAC,OAAO,CAACC,GAAG,CACR,4DAA2DV,IAAI,IAAI,EAAG,GACzE,CAAC;IACD;EACF;;EACA,MAAMH,WAAW,GAAGO,UAAU,GAAG,IAAAO,QAAI,EAAC,CAAC;EACvC,MAAMC,eAAe,GAAGZ,IAAI,GAAI,GAAEA,IAAK,cAAa,GAAG,aAAa;EACpEE,WAAW,CAACW,GAAG,CAAiBD,eAAe,EAAEf,WAAW,CAAC;EAC7D,MAAMF,IAAI,GAAG,MAAMM,MAAM,CACvBE,OAAO,IAAKD,W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EA,MAAM,CAACE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjCzC,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLE,IAAI,EAAE4B,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGqB,UAAU,CAAC1C,SAAS,GAAG,IAAI,GAAG0C,UAAU,CAAC7C,IAAI;IACzE+C,OAAO,EAAEC,OAAO,CAACH,UAAU,CAAC3C,WAAW,CAAC;IAExC+C,MAAM,EAAGC,YAAsC,IAAK9C,IAAI,CACtDC,IAAI,EACJ6C,YAAY,IAAI5C,MAAM,EACtBC,WAAW,EACX,IACF,CAAC;IAEDJ,SAAS,EAAE0C,UAAU,CAAC1C;EACxB,CAAC;AACH;AAAC,IAAAgD,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEc3B,YAAY"}
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["useAsyncData","useAsyncCollection","id","path","loader","options","arguments","length","undefined","itemPath","oldData"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>\n >,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,OAAOA,YAAY;;AAWnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAyBA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EAEZ;EAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAElC,MAAMG,QAAQ,GAAGN,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAOF,YAAY,CACjBS,QAAQ,EACPC,OAAqB,IAAKN,MAAM,CAACF,EAAE,EAAEQ,OAAO,CAAC,EAC9CL,OACF,CAAC;AACH;AAEA,eAAeJ,kBAAkB"}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["useAsyncData","useAsyncCollection","id","path","loader","options","arguments","length","undefined","itemPath","oldData"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,OAAOA,YAAY;;AAWnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AA0BA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EAEZ;EAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAElC,MAAMG,QAAQ,GAAGN,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAOF,YAAY,CACjBS,QAAQ,EACPC,OAAqB,IAAKN,MAAM,CAACF,EAAE,EAAEQ,OAAO,CAAC,EAC9CL,OACF,CAAC;AACH;AAEA,eAAeJ,kBAAkB"}
@@ -192,6 +192,7 @@ function useAsyncData(path, loader) {
192
192
  return {
193
193
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
194
194
  loading: Boolean(localState.operationId),
195
+ reload: customLoader => load(path, customLoader || loader, globalState, null),
195
196
  timestamp: localState.timestamp
196
197
  };
197
198
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","get","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState, null);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MA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zEuC,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACpC,WAAW,CAAC;IACxCC,SAAS,EAAEmC,UAAU,CAACnC;EACxB,CAAC;AACH;AAEA,eAAeoB,YAAY"}
1
+ {"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","get","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","localState","loading","Boolean","reload","customLoader"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState, null);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n\n reload: (customLoader?: AsyncDataLoaderT<DataT>) => load(\n path,\n customLoader || loader,\n globalState,\n null,\n ),\n\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MAAM,CAAC,CAAC;;AAYnC,OAAO,SAASK,oBAAoBA,CAAA,EAEP;EAAA,IAD3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAEhC,OAAO;IACLG,IAAI,EAAEJ,WAAW;IACjBK,OAAO,EAAE,CAAC;IACVC,WAAW,EAAE,EAAE;IACfC,SAAS,EAAE;EACb,CAAC;AACH;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,IAAIA,CACjBC,IAA+B,EAC/BC,MAA+B,EAC/BC,WAAsD,EACtDC,OAAqB,EAEN;EAAA,IADfC,UAAqB,GAAAZ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,GAAG;EAE3B,IAAIa,OAAO,CA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KAAK,GAAG,CAAC,EAAE;QAChEhC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE2B,MAAM,CAAClC,IAAI,CAAC;QAC5CmC,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;;IAEF,MAAME,IAAI,GAAGb,OAAO,CAACa,IAAI,IAAI,EAAE;IAC/BlD,SAAS,CAAC,MAAM;MAAE;MAChB,IAAI,CAACgD,aAAa,IAAIE,IAAI,CAACvC,MAAM,EAAEM,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;IAC1E,CAAC,EAAE8B,IAAI,CAAC,CAAC,CAAC;EACZ;;EAEA,MAAM,CAACC,UAAU,CAAC,GAAG9C,cAAc,CACjCa,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLK,IAAI,EAAEyB,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGiB,UAAU,CAACnC,SAAS,GAAG,IAAI,GAAGmC,UAAU,CAACtC,IAAI;IACzEuC,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACpC,WAAW,CAAC;IAExCuC,MAAM,EAAGC,YAAsC,IAAKtC,IAAI,CACtDC,IAAI,EACJqC,YAAY,IAAIpC,MAAM,EACtBC,WAAW,EACX,IACF,CAAC;IAEDJ,SAAS,EAAEmC,UAAU,CAACnC;EACxB,CAAC;AACH;AAEA,eAAeoB,YAAY"}
@@ -46,7 +46,7 @@ export type AsyncCollectionLoaderT<DataT> = (id: string, oldData: null | DataT)
46
46
  * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
47
47
  * `useAsyncData()` hooks logic.
48
48
  */
49
- declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
49
+ declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT>;
50
50
  declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
51
51
  export default useAsyncCollection;
52
52
  export interface UseAsyncCollectionI<StateT> {
@@ -20,6 +20,7 @@ export type UseAsyncDataOptionsT = {
20
20
  export type UseAsyncDataResT<DataT> = {
21
21
  data: DataT | null;
22
22
  loading: boolean;
23
+ reload: (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;
23
24
  timestamp: number;
24
25
  };
25
26
  /**
@@ -70,7 +71,7 @@ export type UseAsyncDataResT<DataT> = {
70
71
  * `useAsyncData()` hooks logic.
71
72
  */
72
73
  export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined> = ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown> ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null> : void;
73
- declare function useAsyncData<StateT, PathT extends null | string | undefined>(path: PathT, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
74
+ declare function useAsyncData<StateT, PathT extends null | string | undefined, DataT extends DataInEnvelopeAtPathT<StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>>(path: PathT, loader: AsyncDataLoaderT<DataT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT>;
74
75
  declare function useAsyncData<Forced extends ForceT | LockT = LockT, DataT = void>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
75
76
  export default useAsyncData;
76
77
  export interface UseAsyncDataI<StateT> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.10.0-alpha.5",
3
+ "version": "0.10.0-alpha.7",
4
4
  "description": "Hook-based global state for React",
5
5
  "main": "./build/common/index.js",
6
6
  "react-native": "src/index.ts",
@@ -45,38 +45,38 @@
45
45
  "dependencies": {
46
46
  "@babel/runtime": "^7.23.2",
47
47
  "@dr.pogodin/js-utils": "^0.0.6",
48
+ "@types/lodash": "^4.14.201",
48
49
  "lodash": "^4.17.21",
49
50
  "uuid": "^9.0.1"
50
51
  },
51
52
  "devDependencies": {
52
53
  "@babel/cli": "^7.23.0",
53
- "@babel/core": "^7.23.2",
54
- "@babel/eslint-parser": "^7.22.15",
54
+ "@babel/core": "^7.23.3",
55
+ "@babel/eslint-parser": "^7.23.3",
55
56
  "@babel/eslint-plugin": "^7.22.10",
56
57
  "@babel/node": "^7.22.19",
57
- "@babel/plugin-transform-runtime": "^7.23.2",
58
- "@babel/preset-env": "^7.23.2",
59
- "@babel/preset-react": "^7.22.15",
60
- "@babel/preset-typescript": "^7.23.2",
58
+ "@babel/plugin-transform-runtime": "^7.23.3",
59
+ "@babel/preset-env": "^7.23.3",
60
+ "@babel/preset-react": "^7.23.3",
61
+ "@babel/preset-typescript": "^7.23.3",
61
62
  "@tsconfig/recommended": "^1.0.3",
62
63
  "@tsd/typescript": "^5.2.2",
63
- "@types/jest": "^29.5.6",
64
- "@types/lodash": "^4.14.200",
65
- "@types/pretty": "^2.0.2",
66
- "@types/react": "^18.2.31",
67
- "@types/react-dom": "^18.2.14",
68
- "@types/uuid": "^9.0.6",
69
- "@typescript-eslint/eslint-plugin": "^6.9.0",
70
- "@typescript-eslint/parser": "^6.9.0",
64
+ "@types/jest": "^29.5.8",
65
+ "@types/pretty": "^2.0.3",
66
+ "@types/react": "^18.2.37",
67
+ "@types/react-dom": "^18.2.15",
68
+ "@types/uuid": "^9.0.7",
69
+ "@typescript-eslint/eslint-plugin": "^6.11.0",
70
+ "@typescript-eslint/parser": "^6.11.0",
71
71
  "babel-jest": "^29.7.0",
72
72
  "babel-plugin-module-resolver": "^5.0.0",
73
- "eslint": "^8.52.0",
73
+ "eslint": "^8.53.0",
74
74
  "eslint-config-airbnb": "^19.0.4",
75
75
  "eslint-config-airbnb-typescript": "^17.1.0",
76
76
  "eslint-import-resolver-babel-module": "^5.3.2",
77
77
  "eslint-plugin-import": "^2.29.0",
78
- "eslint-plugin-jest": "^27.4.3",
79
- "eslint-plugin-jsx-a11y": "^6.7.1",
78
+ "eslint-plugin-jest": "^27.6.0",
79
+ "eslint-plugin-jsx-a11y": "^6.8.0",
80
80
  "eslint-plugin-react": "^7.33.2",
81
81
  "eslint-plugin-react-hooks": "^4.6.0",
82
82
  "jest": "^29.7.0",
@@ -60,14 +60,15 @@ function useAsyncCollection<
60
60
  StateT,
61
61
  PathT extends null | string | undefined,
62
62
  IdT extends string,
63
+
64
+ DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =
65
+ DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,
63
66
  >(
64
67
  id: IdT,
65
68
  path: PathT,
66
- loader: AsyncCollectionLoaderT<
67
- DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>
68
- >,
69
+ loader: AsyncCollectionLoaderT<DataT>,
69
70
  options?: UseAsyncDataOptionsT,
70
- ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
71
+ ): UseAsyncDataResT<DataT>;
71
72
 
72
73
  function useAsyncCollection<
73
74
  Forced extends ForceT | LockT = LockT,
@@ -56,6 +56,7 @@ export type UseAsyncDataOptionsT = {
56
56
  export type UseAsyncDataResT<DataT> = {
57
57
  data: DataT | null;
58
58
  loading: boolean;
59
+ reload: (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;
59
60
  timestamp: number;
60
61
  };
61
62
 
@@ -175,11 +176,14 @@ export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefine
175
176
  function useAsyncData<
176
177
  StateT,
177
178
  PathT extends null | string | undefined,
179
+
180
+ DataT extends DataInEnvelopeAtPathT<StateT, PathT> =
181
+ DataInEnvelopeAtPathT<StateT, PathT>,
178
182
  >(
179
183
  path: PathT,
180
- loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,
184
+ loader: AsyncDataLoaderT<DataT>,
181
185
  options?: UseAsyncDataOptionsT,
182
- ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
186
+ ): UseAsyncDataResT<DataT>;
183
187
 
184
188
  function useAsyncData<
185
189
  Forced extends ForceT | LockT = LockT,
@@ -289,6 +293,14 @@ function useAsyncData<DataT>(
289
293
  return {
290
294
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
291
295
  loading: Boolean(localState.operationId),
296
+
297
+ reload: (customLoader?: AsyncDataLoaderT<DataT>) => load(
298
+ path,
299
+ customLoader || loader,
300
+ globalState,
301
+ null,
302
+ ),
303
+
292
304
  timestamp: localState.timestamp,
293
305
  };
294
306
  }