@dr.pogodin/react-global-state 0.17.4 → 0.17.5

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.
@@ -146,14 +146,18 @@ function useAsyncData(path, loader, options = {}) {
146
146
  return load(heap.path, localLoader, heap.globalState);
147
147
  };
148
148
  }
149
- if (globalState.ssrContext && !options.noSSR) {
150
- if (!state.timestamp && !state.operationId) {
149
+ if (globalState.ssrContext) {
150
+ if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
151
151
  globalState.ssrContext.pending.push(load(path, loader, globalState, {
152
152
  data: state.data,
153
153
  timestamp: state.timestamp
154
154
  }, `S${(0, _uuid.v4)()}`));
155
155
  }
156
156
  } else {
157
+ const {
158
+ disabled
159
+ } = options;
160
+
157
161
  // This takes care about the client-side reference counting, and garbage
158
162
  // collection.
159
163
  //
@@ -166,26 +170,30 @@ function useAsyncData(path, loader, options = {}) {
166
170
  (0, _react.useEffect)(() => {
167
171
  // eslint-disable-line react-hooks/rules-of-hooks
168
172
  const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
169
- const numRefs = globalState.get(numRefsPath);
170
- globalState.set(numRefsPath, numRefs + 1);
173
+ if (!disabled) {
174
+ const numRefs = globalState.get(numRefsPath);
175
+ globalState.set(numRefsPath, numRefs + 1);
176
+ }
171
177
  return () => {
172
- const state2 = globalState.get(path);
173
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
174
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
175
- /* eslint-disable no-console */
176
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
177
- /* eslint-enable no-console */
178
- }
179
- globalState.dropDependencies(path || '');
180
- globalState.set(path, {
181
- ...state2,
182
- data: null,
183
- numRefs: 0,
184
- timestamp: 0
185
- });
186
- } else globalState.set(numRefsPath, state2.numRefs - 1);
178
+ if (!disabled) {
179
+ const state2 = globalState.get(path);
180
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
181
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
182
+ /* eslint-disable no-console */
183
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
184
+ /* eslint-enable no-console */
185
+ }
186
+ globalState.dropDependencies(path || '');
187
+ globalState.set(path, {
188
+ ...state2,
189
+ data: null,
190
+ numRefs: 0,
191
+ timestamp: 0
192
+ });
193
+ } else globalState.set(numRefsPath, state2.numRefs - 1);
194
+ }
187
195
  };
188
- }, [garbageCollectAge, globalState, path]);
196
+ }, [disabled, garbageCollectAge, globalState, path]);
189
197
 
190
198
  // Note: a bunch of Rules of Hooks ignored belows because in our very
191
199
  // special case the otherwise wrong behavior is actually what we need.
@@ -193,22 +201,24 @@ function useAsyncData(path, loader, options = {}) {
193
201
  // Data loading and refreshing.
194
202
  (0, _react.useEffect)(() => {
195
203
  // eslint-disable-line react-hooks/rules-of-hooks
196
- const state2 = globalState.get(path);
197
- const {
198
- deps
199
- } = options;
200
- if (
201
- // The hook is called with a list of dependencies, that mismatch
202
- // dependencies last used to retrieve the data at given path.
203
- deps && globalState.hasChangedDependencies(path || '', deps)
204
+ if (!disabled) {
205
+ const state2 = globalState.get(path);
206
+ const {
207
+ deps
208
+ } = options;
209
+ if (
210
+ // The hook is called with a list of dependencies, that mismatch
211
+ // dependencies last used to retrieve the data at given path.
212
+ deps && globalState.hasChangedDependencies(path || '', deps)
204
213
 
205
- // Data at the path are stale, and are not being loaded.
206
- || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
207
- if (!deps) globalState.dropDependencies(path || '');
208
- load(path, loader, globalState, {
209
- data: state2.data,
210
- timestamp: state2.timestamp
211
- });
214
+ // Data at the path are stale, and are not being loaded.
215
+ || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
216
+ if (!deps) globalState.dropDependencies(path || '');
217
+ load(path, loader, globalState, {
218
+ data: state2.data,
219
+ timestamp: state2.timestamp
220
+ });
221
+ }
212
222
  }
213
223
  });
214
224
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","load","path","loader","globalState","old","uuid","process","env","NODE_ENV","isDebugMode","console","log","operationIdPath","prevOperationId","get","asyncDataLoadDone","set","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","state","groupCollapsed","cloneDeepForLog","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","charAt","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } 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 cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\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: AsyncDataReloaderT<DataT>;\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 */\nexport async function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null, timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n let data: DataT | null;\n\n try {\n data = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\n } finally {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n }\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\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.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\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 ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\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 const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n }\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\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.dropDependencies(path || '');\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 useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path || '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(path || '');\n load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n });\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 reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { 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,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBO,MAAMO,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG,CAAC,GAAGE,eAAM,CAAC,CAAC;;AAqBnC,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAAS,GAAG;AAAE,CAAC,GAAG,CAAC,CAAC,EACR;EAC3B,OAAO;IACLC,IAAI,EAAEH,WAAW;IACjBC,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAiBA;AACA;AACA;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oreList":[]}
1
+ {"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","load","path","loader","globalState","old","uuid","process","env","NODE_ENV","isDebugMode","console","log","operationIdPath","prevOperationId","get","asyncDataLoadDone","set","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","state","groupCollapsed","cloneDeepForLog","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","disabled","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","charAt","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } 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 cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\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: AsyncDataReloaderT<DataT>;\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 */\nexport async function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null, timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n let data: DataT | null;\n\n try {\n data = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\n } finally {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n }\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\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.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\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 ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\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 const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n }\n\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\n );\n }\n } else {\n const { disabled } = options;\n\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 if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\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.dropDependencies(path || '');\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 };\n }, [disabled, 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 useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path || '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(path || '');\n load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\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 reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { 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,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBO,MAAMO,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG,CAAC,GAAGE,eAAM,CAAC,CAAC;;AAqBnC,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAAS,GAAG;AAAE,CAAC,GAAG,CAAC,CAAC,EACR;EAC3B,OAAO;IACLC,IAAI,EAAEH,WAAW;IACjBC,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAkBA;AACA;A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,CAAC9D,SAAS,GAAG,IAAI,GAAG8D,UAAU,CAAC7D,IAAI;IACzE+D,OAAO,EAAEC,OAAO,CAACH,UAAU,CAAC5D,WAAW,CAAC;IACxC6C,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnB/C,SAAS,EAAE8D,UAAU,CAAC9D;EACxB,CAAC;AACH","ignoreList":[]}
@@ -136,14 +136,18 @@ function useAsyncData(path, loader) {
136
136
  return load(heap.path, localLoader, heap.globalState);
137
137
  };
138
138
  }
139
- if (globalState.ssrContext && !options.noSSR) {
140
- if (!state.timestamp && !state.operationId) {
139
+ if (globalState.ssrContext) {
140
+ if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
141
141
  globalState.ssrContext.pending.push(load(path, loader, globalState, {
142
142
  data: state.data,
143
143
  timestamp: state.timestamp
144
144
  }, `S${uuid()}`));
145
145
  }
146
146
  } else {
147
+ const {
148
+ disabled
149
+ } = options;
150
+
147
151
  // This takes care about the client-side reference counting, and garbage
148
152
  // collection.
149
153
  //
@@ -156,26 +160,30 @@ function useAsyncData(path, loader) {
156
160
  useEffect(() => {
157
161
  // eslint-disable-line react-hooks/rules-of-hooks
158
162
  const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
159
- const numRefs = globalState.get(numRefsPath);
160
- globalState.set(numRefsPath, numRefs + 1);
163
+ if (!disabled) {
164
+ const numRefs = globalState.get(numRefsPath);
165
+ globalState.set(numRefsPath, numRefs + 1);
166
+ }
161
167
  return () => {
162
- const state2 = globalState.get(path);
163
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
164
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
165
- /* eslint-disable no-console */
166
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
167
- /* eslint-enable no-console */
168
- }
169
- globalState.dropDependencies(path || '');
170
- globalState.set(path, {
171
- ...state2,
172
- data: null,
173
- numRefs: 0,
174
- timestamp: 0
175
- });
176
- } else globalState.set(numRefsPath, state2.numRefs - 1);
168
+ if (!disabled) {
169
+ const state2 = globalState.get(path);
170
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
171
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
172
+ /* eslint-disable no-console */
173
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
174
+ /* eslint-enable no-console */
175
+ }
176
+ globalState.dropDependencies(path || '');
177
+ globalState.set(path, {
178
+ ...state2,
179
+ data: null,
180
+ numRefs: 0,
181
+ timestamp: 0
182
+ });
183
+ } else globalState.set(numRefsPath, state2.numRefs - 1);
184
+ }
177
185
  };
178
- }, [garbageCollectAge, globalState, path]);
186
+ }, [disabled, garbageCollectAge, globalState, path]);
179
187
 
180
188
  // Note: a bunch of Rules of Hooks ignored belows because in our very
181
189
  // special case the otherwise wrong behavior is actually what we need.
@@ -183,22 +191,24 @@ function useAsyncData(path, loader) {
183
191
  // Data loading and refreshing.
184
192
  useEffect(() => {
185
193
  // eslint-disable-line react-hooks/rules-of-hooks
186
- const state2 = globalState.get(path);
187
- const {
188
- deps
189
- } = options;
190
- if (
191
- // The hook is called with a list of dependencies, that mismatch
192
- // dependencies last used to retrieve the data at given path.
193
- deps && globalState.hasChangedDependencies(path || '', deps)
194
+ if (!disabled) {
195
+ const state2 = globalState.get(path);
196
+ const {
197
+ deps
198
+ } = options;
199
+ if (
200
+ // The hook is called with a list of dependencies, that mismatch
201
+ // dependencies last used to retrieve the data at given path.
202
+ deps && globalState.hasChangedDependencies(path || '', deps)
194
203
 
195
- // Data at the path are stale, and are not being loaded.
196
- || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
197
- if (!deps) globalState.dropDependencies(path || '');
198
- load(path, loader, globalState, {
199
- data: state2.data,
200
- timestamp: state2.timestamp
201
- });
204
+ // Data at the path are stale, and are not being loaded.
205
+ || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
206
+ if (!deps) globalState.dropDependencies(path || '');
207
+ load(path, loader, globalState, {
208
+ data: state2.data,
209
+ timestamp: state2.timestamp
210
+ });
211
+ }
202
212
  }
203
213
  });
204
214
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","numRefs","timestamp","data","operationId","load","path","loader","globalState","old","process","env","NODE_ENV","console","log","operationIdPath","prevOperationId","get","asyncDataLoadDone","set","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","state","groupCollapsed","Date","now","groupEnd","useAsyncData","_options$maxage","_options$refreshAge","_options$garbageColle","options","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","ssrContext","noSSR","pending","push","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","charAt","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } 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 cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\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: AsyncDataReloaderT<DataT>;\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 */\nexport async function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null, timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n let data: DataT | null;\n\n try {\n data = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\n } finally {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n }\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\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.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\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 ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\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 const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n }\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\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.dropDependencies(path || '');\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 useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path || '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(path || '');\n load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n });\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 reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { 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,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,eAAe,EACfC,WAAW;AAMb,OAAO,MAAMC,cAAc,GAAG,CAAC,GAAGL,MAAM,CAAC,CAAC;;AAqB1C,OAAO,SAASM,oBAAoBA,CAAA,EAGP;EAAA,IAF3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAAA,IAChC;IAAEG,OAAO,GAAG,CAAC;IAAEC,SAAS,GAAG;EAAE,CAAC,GAAAJ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SA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;IACF,CAAC,CAAC;EACJ;EAEA,MAAM,CAAC0D,UAAU,CAAC,GAAGpE,cAAc,CACjCc,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLO,IAAI,EAAEsC,MAAM,GAAGR,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG0B,UAAU,CAAC1D,SAAS,GAAG,IAAI,GAAG0D,UAAU,CAACzD,IAAI;IACzE0D,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACxD,WAAW,CAAC;IACxC2C,MAAM,EAAED,IAAI,CAACC,MAAM;IACnB7C,SAAS,EAAE0D,UAAU,CAAC1D;EACxB,CAAC;AACH;AAEA,SAASkC,YAAY","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","numRefs","timestamp","data","operationId","load","path","loader","globalState","old","process","env","NODE_ENV","console","log","operationIdPath","prevOperationId","get","asyncDataLoadDone","set","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","state","groupCollapsed","Date","now","groupEnd","useAsyncData","_options$maxage","_options$refreshAge","_options$garbageColle","options","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","ssrContext","disabled","noSSR","pending","push","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","charAt","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } 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 cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\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: AsyncDataReloaderT<DataT>;\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 */\nexport async function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null, timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n let data: DataT | null;\n\n try {\n data = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\n } finally {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n }\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\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.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\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 ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\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 const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n }\n\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\n );\n }\n } else {\n const { disabled } = options;\n\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 if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\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.dropDependencies(path || '');\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 };\n }, [disabled, 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 useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path || '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(path || '');\n load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\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 reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { 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,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SA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AAC;QAExC,MAAM;UAAEoD;QAAK,CAAC,GAAGlB,OAAO;QACxB;QACE;QACA;QACCkB,IAAI,IAAIlD,WAAW,CAACmD,sBAAsB,CAACrD,IAAI,IAAI,EAAE,EAAEoD,IAAI;;QAE5D;QAAA,GAEEhB,UAAU,GAAGT,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGsB,MAAM,CAACtD,SAAS,KACtC,CAACsD,MAAM,CAACpD,WAAW,IAAIoD,MAAM,CAACpD,WAAW,CAACwD,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,CAChE,EACD;UACA,IAAI,CAACF,IAAI,EAAElD,WAAW,CAACiD,gBAAgB,CAACnD,IAAI,IAAI,EAAE,CAAC;UACnDD,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE;YAC9BL,IAAI,EAAEqD,MAAM,CAACrD,IAAI;YACjBD,SAAS,EAAEsD,MAAM,CAACtD;UACpB,CAAC,CAAC;QACJ;MACF;IACF,CAAC,CAAC;EACJ;EAEA,MAAM,CAAC2D,UAAU,CAAC,GAAGrE,cAAc,CACjCc,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLO,IAAI,EAAEsC,MAAM,GAAGR,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG2B,UAAU,CAAC3D,SAAS,GAAG,IAAI,GAAG2D,UAAU,CAAC1D,IAAI;IACzE2D,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACzD,WAAW,CAAC;IACxC2C,MAAM,EAAED,IAAI,CAACC,MAAM;IACnB7C,SAAS,EAAE2D,UAAU,CAAC3D;EACxB,CAAC;AACH;AAEA,SAASkC,YAAY","ignoreList":[]}
@@ -24,6 +24,7 @@ export declare function newAsyncDataEnvelope<DataT>(initialData?: DataT | null,
24
24
  }): AsyncDataEnvelopeT<DataT>;
25
25
  export type UseAsyncDataOptionsT = {
26
26
  deps?: unknown[];
27
+ disabled?: boolean;
27
28
  garbageCollectAge?: number;
28
29
  maxage?: number;
29
30
  noSSR?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.17.4",
3
+ "version": "0.17.5",
4
4
  "description": "Hook-based global state for React",
5
5
  "main": "./build/common/index.js",
6
6
  "react-native": "src/index.ts",
@@ -43,48 +43,47 @@
43
43
  "node": ">=18"
44
44
  },
45
45
  "dependencies": {
46
- "@babel/runtime": "^7.25.6",
46
+ "@babel/runtime": "^7.26.0",
47
47
  "@dr.pogodin/js-utils": "^0.0.12",
48
- "@types/lodash": "^4.17.7",
48
+ "@types/lodash": "^4.17.13",
49
49
  "lodash": "^4.17.21",
50
- "uuid": "^10.0.0"
50
+ "uuid": "^11.0.3"
51
51
  },
52
52
  "devDependencies": {
53
- "@babel/cli": "^7.25.6",
54
- "@babel/core": "^7.25.2",
55
- "@babel/eslint-parser": "^7.25.1",
56
- "@babel/eslint-plugin": "^7.25.1",
57
- "@babel/node": "^7.25.0",
58
- "@babel/plugin-transform-runtime": "^7.25.4",
59
- "@babel/preset-env": "^7.25.4",
60
- "@babel/preset-react": "^7.24.7",
61
- "@babel/preset-typescript": "^7.24.7",
53
+ "@babel/cli": "^7.25.9",
54
+ "@babel/core": "^7.26.0",
55
+ "@babel/eslint-parser": "^7.25.9",
56
+ "@babel/eslint-plugin": "^7.25.9",
57
+ "@babel/node": "^7.26.0",
58
+ "@babel/plugin-transform-runtime": "^7.25.9",
59
+ "@babel/preset-env": "^7.26.0",
60
+ "@babel/preset-react": "^7.25.9",
61
+ "@babel/preset-typescript": "^7.26.0",
62
62
  "@testing-library/dom": "^10.4.0",
63
63
  "@testing-library/react": "^16.0.1",
64
- "@tsconfig/recommended": "^1.0.7",
65
- "@types/jest": "^29.5.13",
64
+ "@tsconfig/recommended": "^1.0.8",
65
+ "@types/jest": "^29.5.14",
66
66
  "@types/pretty": "^2.0.3",
67
- "@types/react": "^18.3.5",
68
- "@types/react-dom": "^18.3.0",
69
- "@types/uuid": "^10.0.0",
67
+ "@types/react": "^18.3.12",
68
+ "@types/react-dom": "^18.3.1",
70
69
  "babel-jest": "^29.7.0",
71
70
  "babel-plugin-module-resolver": "^5.0.2",
72
- "eslint": "^8.57.0",
71
+ "eslint": "^8.57.1",
73
72
  "eslint-config-airbnb": "^19.0.4",
74
73
  "eslint-config-airbnb-typescript": "^18.0.0",
75
74
  "eslint-import-resolver-babel-module": "^5.3.2",
76
- "eslint-plugin-import": "^2.30.0",
77
- "eslint-plugin-jest": "^28.8.3",
78
- "eslint-plugin-jsx-a11y": "^6.10.0",
79
- "eslint-plugin-react": "^7.36.1",
75
+ "eslint-plugin-import": "^2.31.0",
76
+ "eslint-plugin-jest": "^28.9.0",
77
+ "eslint-plugin-jsx-a11y": "^6.10.2",
78
+ "eslint-plugin-react": "^7.37.2",
80
79
  "eslint-plugin-react-hooks": "^4.6.2",
81
80
  "jest": "^29.7.0",
82
81
  "jest-environment-jsdom": "^29.7.0",
83
82
  "mockdate": "^3.0.5",
84
83
  "rimraf": "^6.0.1",
85
- "tstyche": "^2.1.1",
86
- "typescript": "^5.6.2",
87
- "typescript-eslint": "^8.5.0"
84
+ "tstyche": "^3.0.0",
85
+ "typescript": "^5.6.3",
86
+ "typescript-eslint": "^8.15.0"
88
87
  },
89
88
  "peerDependencies": {
90
89
  "react": "^18.3.1",
@@ -57,6 +57,7 @@ export function newAsyncDataEnvelope<DataT>(
57
57
 
58
58
  export type UseAsyncDataOptionsT = {
59
59
  deps?: unknown[];
60
+ disabled?: boolean;
60
61
  garbageCollectAge?: number;
61
62
  maxage?: number;
62
63
  noSSR?: boolean;
@@ -242,8 +243,8 @@ function useAsyncData<DataT>(
242
243
  };
243
244
  }
244
245
 
245
- if (globalState.ssrContext && !options.noSSR) {
246
- if (!state.timestamp && !state.operationId) {
246
+ if (globalState.ssrContext) {
247
+ if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
247
248
  globalState.ssrContext.pending.push(
248
249
  load(path, loader, globalState, {
249
250
  data: state.data,
@@ -252,6 +253,8 @@ function useAsyncData<DataT>(
252
253
  );
253
254
  }
254
255
  } else {
256
+ const { disabled } = options;
257
+
255
258
  // This takes care about the client-side reference counting, and garbage
256
259
  // collection.
257
260
  //
@@ -263,62 +266,68 @@ function useAsyncData<DataT>(
263
266
  // The same applies to other useEffect() hooks below.
264
267
  useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
265
268
  const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
266
- const numRefs = globalState.get<ForceT, number>(numRefsPath);
267
- globalState.set<ForceT, number>(numRefsPath, numRefs + 1);
269
+ if (!disabled) {
270
+ const numRefs = globalState.get<ForceT, number>(numRefsPath);
271
+ globalState.set<ForceT, number>(numRefsPath, numRefs + 1);
272
+ }
268
273
  return () => {
269
- const state2: AsyncDataEnvelopeT<DataT> = globalState.get<
270
- ForceT, AsyncDataEnvelopeT<DataT>>(
271
- path,
272
- );
273
- if (
274
- state2.numRefs === 1
275
- && garbageCollectAge < Date.now() - state2.timestamp
276
- ) {
277
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
278
- /* eslint-disable no-console */
279
- console.log(
280
- `ReactGlobalState - useAsyncData garbage collected at path ${
281
- path || ''
282
- }`,
283
- );
284
- /* eslint-enable no-console */
285
- }
286
- globalState.dropDependencies(path || '');
287
- globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {
288
- ...state2,
289
- data: null,
290
- numRefs: 0,
291
- timestamp: 0,
292
- });
293
- } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);
274
+ if (!disabled) {
275
+ const state2: AsyncDataEnvelopeT<DataT> = globalState.get<
276
+ ForceT, AsyncDataEnvelopeT<DataT>>(
277
+ path,
278
+ );
279
+ if (
280
+ state2.numRefs === 1
281
+ && garbageCollectAge < Date.now() - state2.timestamp
282
+ ) {
283
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
284
+ /* eslint-disable no-console */
285
+ console.log(
286
+ `ReactGlobalState - useAsyncData garbage collected at path ${
287
+ path || ''
288
+ }`,
289
+ );
290
+ /* eslint-enable no-console */
291
+ }
292
+ globalState.dropDependencies(path || '');
293
+ globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {
294
+ ...state2,
295
+ data: null,
296
+ numRefs: 0,
297
+ timestamp: 0,
298
+ });
299
+ } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);
300
+ }
294
301
  };
295
- }, [garbageCollectAge, globalState, path]);
302
+ }, [disabled, garbageCollectAge, globalState, path]);
296
303
 
297
304
  // Note: a bunch of Rules of Hooks ignored belows because in our very
298
305
  // special case the otherwise wrong behavior is actually what we need.
299
306
 
300
307
  // Data loading and refreshing.
301
308
  useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
302
- const state2: AsyncDataEnvelopeT<DataT> = globalState.get<
303
- ForceT, AsyncDataEnvelopeT<DataT>>(path);
304
-
305
- const { deps } = options;
306
- if (
307
- // The hook is called with a list of dependencies, that mismatch
308
- // dependencies last used to retrieve the data at given path.
309
- (deps && globalState.hasChangedDependencies(path || '', deps))
310
-
311
- // Data at the path are stale, and are not being loaded.
312
- || (
313
- refreshAge < Date.now() - state2.timestamp
314
- && (!state2.operationId || state2.operationId.charAt(0) === 'S')
315
- )
316
- ) {
317
- if (!deps) globalState.dropDependencies(path || '');
318
- load(path, loader, globalState, {
319
- data: state2.data,
320
- timestamp: state2.timestamp,
321
- });
309
+ if (!disabled) {
310
+ const state2: AsyncDataEnvelopeT<DataT> = globalState.get<
311
+ ForceT, AsyncDataEnvelopeT<DataT>>(path);
312
+
313
+ const { deps } = options;
314
+ if (
315
+ // The hook is called with a list of dependencies, that mismatch
316
+ // dependencies last used to retrieve the data at given path.
317
+ (deps && globalState.hasChangedDependencies(path || '', deps))
318
+
319
+ // Data at the path are stale, and are not being loaded.
320
+ || (
321
+ refreshAge < Date.now() - state2.timestamp
322
+ && (!state2.operationId || state2.operationId.charAt(0) === 'S')
323
+ )
324
+ ) {
325
+ if (!deps) globalState.dropDependencies(path || '');
326
+ load(path, loader, globalState, {
327
+ data: state2.data,
328
+ timestamp: state2.timestamp,
329
+ });
330
+ }
322
331
  }
323
332
  });
324
333
  }