@dr.pogodin/react-global-state 0.19.0 → 0.19.2
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.
- package/build/cjs/GlobalState.js +289 -0
- package/build/cjs/GlobalState.js.map +1 -0
- package/build/cjs/GlobalStateProvider.js +97 -0
- package/build/cjs/GlobalStateProvider.js.map +1 -0
- package/build/cjs/SsrContext.js +15 -0
- package/build/cjs/SsrContext.js.map +1 -0
- package/build/cjs/index.js +88 -0
- package/build/cjs/index.js.map +1 -0
- package/build/cjs/useAsyncCollection.js +270 -0
- package/build/cjs/useAsyncCollection.js.map +1 -0
- package/build/cjs/useAsyncData.js +260 -0
- package/build/cjs/useAsyncData.js.map +1 -0
- package/build/cjs/useGlobalState.js +149 -0
- package/build/cjs/useGlobalState.js.map +1 -0
- package/build/cjs/utils.js +91 -0
- package/build/cjs/utils.js.map +1 -0
- package/build/code/useAsyncCollection.js +7 -10
- package/build/code/useAsyncCollection.js.map +1 -1
- package/build/code/useAsyncData.js +56 -31
- package/build/code/useAsyncData.js.map +1 -1
- package/build/types/useAsyncCollection.d.ts +2 -2
- package/build/types/useAsyncData.d.ts +3 -3
- package/package.json +4 -2
|
@@ -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","_heap$reload","options","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","ssrContext","disabled","noSSR","pending","push","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","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 type GlobalState from './GlobalState';\nimport type 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<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n 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<\n StateT, PathT> = 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 heap.reload ??= async (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 if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\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 {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\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.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n void 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\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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,SAAA,MAAG,CAAC,CAAC;EAEnC,OAAO;IACLK,IAAI,EAAEN,WAAW;IACjBI,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeG,IAAIA,CACxBC,IAA+B,EAC/BC,MAA+B,EAC/BC,WAAsD,EACtDC,GAA+C,EAOhC;EAAA,IADfL,WAAyB,GAAAN,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAIT,IAAI,CAAC,CAAC,EAAE;EAExC,IAAIqB,OAAO,CAACC,G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,CAAC;EACJ;EAEA,MAAM,CAAC4D,UAAU,CAAC,GAAGtE,cAAc,CACjCc,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLO,IAAI,EAAEuC,MAAM,GAAGT,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG4B,UAAU,CAAC5D,SAAS,GAAG,IAAI,GAAG4D,UAAU,CAAC3D,IAAI;IACzE4D,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC1D,WAAW,CAAC;IACxC4C,MAAM,EAAED,IAAI,CAACC,MAAM;IACnB9C,SAAS,EAAE4D,UAAU,CAAC5D;EACxB,CAAC;AACH;AAEA,SAASkC,YAAY;;AAErB","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","finalizeLoad","path","globalState","asyncDataLoadDone","state","get","process","env","NODE_ENV","console","groupCollapsed","log","set","Date","now","groupEnd","load","loader","old","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","useAsyncData","_options$maxage","_options$refreshAge","_options$garbageColle","_heap$reload","options","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","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 type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => (DataT | null) | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => void | 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\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\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 //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n globalState.asyncDataLoadDone(operationId, false);\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 * 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 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): void | 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<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n 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 if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\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\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\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<\n StateT, PathT> = 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 heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\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 if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\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 {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\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.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n void 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\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBA,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,SAAA,MAAG,CAAC,CAAC;EAEnC,OAAO;IACLK,IAAI,EAAEN,WAAW;IACjBI,OAAO;IACPG,WA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C,YAAY;;AAErB","ignoreList":[]}
|
|
@@ -8,8 +8,8 @@ export type AsyncCollectionLoaderT<DataT, IdT extends number | string = number |
|
|
|
8
8
|
isAborted: () => boolean;
|
|
9
9
|
oldDataTimestamp: number;
|
|
10
10
|
setAbortCallback: (cb: () => void) => void;
|
|
11
|
-
}) => DataT | Promise<DataT | null
|
|
12
|
-
export type AsyncCollectionReloaderT<DataT, IdT extends number | string = number | string> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;
|
|
11
|
+
}) => (DataT | null) | Promise<DataT | null>;
|
|
12
|
+
export type AsyncCollectionReloaderT<DataT, IdT extends number | string = number | string> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | Promise<void>;
|
|
13
13
|
type CollectionItemT<DataT> = {
|
|
14
14
|
data: DataT | null;
|
|
15
15
|
loading: boolean;
|
|
@@ -9,8 +9,8 @@ export type AsyncDataLoaderT<DataT> = (oldData: null | DataT, meta: {
|
|
|
9
9
|
isAborted: () => boolean;
|
|
10
10
|
oldDataTimestamp: number;
|
|
11
11
|
setAbortCallback: (cb: () => void) => void;
|
|
12
|
-
}) => DataT | Promise<DataT | null
|
|
13
|
-
export type AsyncDataReloaderT<DataT> = (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;
|
|
12
|
+
}) => (DataT | null) | Promise<DataT | null>;
|
|
13
|
+
export type AsyncDataReloaderT<DataT> = (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;
|
|
14
14
|
export type AsyncDataEnvelopeT<DataT> = {
|
|
15
15
|
data: null | DataT;
|
|
16
16
|
numRefs: number;
|
|
@@ -53,7 +53,7 @@ export type UseAsyncDataResT<DataT> = {
|
|
|
53
53
|
export declare function load<DataT>(path: null | string | undefined, loader: AsyncDataLoaderT<DataT>, globalState: GlobalState<unknown, SsrContext<unknown>>, old?: {
|
|
54
54
|
data: DataT | null;
|
|
55
55
|
timestamp: number;
|
|
56
|
-
}, operationId?: OperationIdT): Promise<void>;
|
|
56
|
+
}, operationId?: OperationIdT): void | Promise<void>;
|
|
57
57
|
/**
|
|
58
58
|
* Resolves asynchronous data, and stores them at given `path` of global
|
|
59
59
|
* state.
|
package/package.json
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dr.pogodin/react-global-state",
|
|
3
|
-
"version": "0.19.
|
|
3
|
+
"version": "0.19.2",
|
|
4
4
|
"description": "Hook-based global state for React",
|
|
5
5
|
"main": "./build/code/index.js",
|
|
6
6
|
"types": "./build/types/index.d.ts",
|
|
7
7
|
"exports": {
|
|
8
|
+
"require": "./build/cjs/index.js",
|
|
8
9
|
"default": "./build/code/index.js"
|
|
9
10
|
},
|
|
10
11
|
"scripts": {
|
|
11
|
-
"build": "rimraf build && npm run build:types && npm run build:code",
|
|
12
|
+
"build": "rimraf build && npm run build:types && npm run build:code && npm run build:cjs",
|
|
13
|
+
"build:cjs": "rimraf buidl/cjs && babel src -x .ts,.tsx --out-dir build/cjs --source-maps",
|
|
12
14
|
"build:code": "rimraf build/code && babel src -x .ts,.tsx --out-dir build/code --source-maps --config-file ./babel.module.config.js",
|
|
13
15
|
"build:types": "rimraf build/types && tsc --project tsconfig.types.json",
|
|
14
16
|
"jest": "npm run jest:types && npm run jest:logic",
|