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

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.
@@ -11,7 +11,7 @@ var _lodash = require("lodash");
11
11
  var _react = require("react");
12
12
  var _GlobalState = _interopRequireDefault(require("./GlobalState"));
13
13
  var _jsxRuntime = require("react/jsx-runtime");
14
- const context = /*#__PURE__*/(0, _react.createContext)(null);
14
+ const Context = /*#__PURE__*/(0, _react.createContext)(null);
15
15
 
16
16
  /**
17
17
  * Gets {@link GlobalState} instance from the context. In most cases
@@ -20,14 +20,7 @@ const context = /*#__PURE__*/(0, _react.createContext)(null);
20
20
  * @return
21
21
  */
22
22
  function getGlobalState() {
23
- // Here Rules of Hooks are violated because "getGlobalState()" does not follow
24
- // convention that hook names should start with use... This is intentional in
25
- // our case, as getGlobalState() hook is intended for advance scenarious,
26
- // while the normal interaction with the global state should happen via
27
- // another hook, useGlobalState().
28
- /* eslint-disable react-hooks/rules-of-hooks */
29
- const globalState = (0, _react.useContext)(context);
30
- /* eslint-enable react-hooks/rules-of-hooks */
23
+ const globalState = (0, _react.use)(Context);
31
24
  if (!globalState) throw new Error('Missing GlobalStateProvider');
32
25
  return globalState;
33
26
  }
@@ -72,24 +65,23 @@ const GlobalStateProvider = ({
72
65
  children,
73
66
  ...rest
74
67
  }) => {
75
- const state = (0, _react.useRef)();
76
- if (!state.current) {
77
- // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
78
- // graceful compatibility with JavaScript - if "undefined" stateProxy value
79
- // is given, we want to follow the second branch, which creates a new
80
- // GlobalState with whatever intiialState given.
81
- if ('stateProxy' in rest && rest.stateProxy) {
82
- if (rest.stateProxy === true) state.current = getGlobalState();else state.current = rest.stateProxy;
83
- } else {
68
+ const localStateRef = (0, _react.useRef)(undefined);
69
+ let state;
70
+ if ('stateProxy' in rest && rest.stateProxy) {
71
+ localStateRef.current = undefined;
72
+ state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;
73
+ } else {
74
+ if (!localStateRef.current) {
84
75
  const {
85
76
  initialState,
86
77
  ssrContext
87
78
  } = rest;
88
- state.current = new _GlobalState.default((0, _lodash.isFunction)(initialState) ? initialState() : initialState, ssrContext);
79
+ localStateRef.current = new _GlobalState.default((0, _lodash.isFunction)(initialState) ? initialState() : initialState, ssrContext);
89
80
  }
81
+ state = localStateRef.current;
90
82
  }
91
- return /*#__PURE__*/(0, _jsxRuntime.jsx)(context.Provider, {
92
- value: state.current,
83
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)(Context, {
84
+ value: state,
93
85
  children: children
94
86
  });
95
87
  };
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["_lodash","require","_react","_GlobalState","_interopRequireDefault","_jsxRuntime","context","createContext","getGlobalState","globalState","useContext","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","state","useRef","current","stateProxy","initialState","GlobalState","isFunction","jsx","Provider","value","_default","exports","default"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>) => {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAAwC,IAAAI,WAAA,GAAAJ,OAAA;AAKxC,MAAMK,OAAO,gBAAG,IAAAC,oBAAa,EAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAG,IAAAC,iBAAU,EAACJ,OAAO,CAAC;EACvC;EACA,IAAI,CAACG,WAAW,EAAE,MAAM,IAAIE,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOF,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGN,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACM,UAAU,IAAID,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOG,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGA,CAG1B;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,KAAK;EACzE,MAAMC,KAAK,GAAG,IAAAC,aAAM,EAAmC,CAAC;EACxD,IAAI,CAACD,KAAK,CAACE,OAAO,EAAE;IAClB;IACA;IACA;IACA;IACA,IAAI,YAAY,IAAIH,IAAI,IAAIA,IAAI,CAACI,UAAU,EAAE;MAC3C,IAAIJ,IAAI,CAACI,UAAU,KAAK,IAAI,EAAEH,KAAK,CAACE,OAAO,GAAGZ,cAAc,CAAC,CAAC,CAAC,KAC1DU,KAAK,CAACE,OAAO,GAAGH,IAAI,CAACI,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAER;MAAW,CAAC,GAAGG,IAA0C;MAE/EC,KAAK,CAACE,OAAO,GAAG,IAAIG,oBAAW,CAC7B,IAAAC,kBAAU,EAACF,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACE,IAAAT,WAAA,CAAAoB,GAAA,EAACnB,OAAO,CAACoB,QAAQ;IAACC,KAAK,EAAET,KAAK,CAACE,OAAQ;IAAAJ,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB,CAAC;AAAC,IAAAY,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaf,mBAAmB","ignoreList":[]}
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["_lodash","require","_react","_GlobalState","_interopRequireDefault","_jsxRuntime","Context","createContext","getGlobalState","globalState","use","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localStateRef","useRef","undefined","state","stateProxy","current","initialState","GlobalState","isFunction","jsx","value","_default","exports","default"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n use,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst Context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>) => {\n type GST = GlobalState<StateT, SsrContextT>;\n const localStateRef = useRef<GST>(undefined);\n let state: GST;\n if ('stateProxy' in rest && rest.stateProxy) {\n localStateRef.current = undefined;\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else {\n if (!localStateRef.current) {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n localStateRef.current = new GlobalState(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n state = localStateRef.current;\n }\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAAwC,IAAAI,WAAA,GAAAJ,OAAA;AAKxC,MAAMK,OAAO,gBAAG,IAAAC,oBAAa,EAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAGQ;EACpC,MAAMC,WAAW,GAAG,IAAAC,UAAG,EAACJ,OAAO,CAAC;EAChC,IAAI,CAACG,WAAW,EAAE,MAAM,IAAIE,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOF,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGN,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACM,UAAU,IAAID,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOG,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGA,CAG1B;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,KAAK;EAEzE,MAAMC,aAAa,GAAG,IAAAC,aAAM,EAAMC,SAAS,CAAC;EAC5C,IAAIC,KAAU;EACd,IAAI,YAAY,IAAIJ,IAAI,IAAIA,IAAI,CAACK,UAAU,EAAE;IAC3CJ,aAAa,CAACK,OAAO,GAAGH,SAAS;IACjCC,KAAK,GAAGJ,IAAI,CAACK,UAAU,KAAK,IAAI,GAAGd,cAAc,CAAC,CAAC,GAAGS,IAAI,CAACK,UAAU;EACvE,CAAC,MAAM;IACL,IAAI,CAACJ,aAAa,CAACK,OAAO,EAAE;MAC1B,MAAM;QAAEC,YAAY;QAAEV;MAAW,CAAC,GAAGG,IAA0C;MAC/EC,aAAa,CAACK,OAAO,GAAG,IAAIE,oBAAW,CACrC,IAAAC,kBAAU,EAACF,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDV,UACF,CAAC;IACH;IACAO,KAAK,GAAGH,aAAa,CAACK,OAAO;EAC/B;EACA,oBAAO,IAAAlB,WAAA,CAAAsB,GAAA,EAACrB,OAAO;IAACsB,KAAK,EAAEP,KAAM;IAAAL,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAAC,IAAAa,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEahB,mBAAmB","ignoreList":[]}
@@ -92,7 +92,7 @@ function normalizeIds(idOrIds) {
92
92
  * Inits/updates, and returns the heap.
93
93
  */
94
94
  function useHeap(ids, path, loader, gs) {
95
- const ref = (0, _react.useRef)();
95
+ const ref = (0, _react.useRef)(undefined);
96
96
  let heap = ref.current;
97
97
  if (heap) {
98
98
  // Update.
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","gcOnWithhold","ids","path","gs","collection","get","i","length","id","envelope","numRefs","newAsyncDataEnvelope","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","isDebugMode","console","log","normalizeIds","idOrIds","Array","isArray","sort","useHeap","loader","ref","useRef","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","load","oldData","meta","reloadSingle","args","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","noSSR","operationId","uuid","state","initialValue","pending","push","data","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","charAt","dropDependencies","old","localState","useGlobalState","e","loading","items","Number","MAX_VALUE","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = { [id in IdT]?: AsyncDataEnvelopeT<DataT> };\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> =\n (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: {\n [id in IdT]: CollectionItemT<DataT>;\n }\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype HeapT<\n DataT,\n IdT extends number | string,\n> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState: GlobalState<unknown>;\n ids: IdT[];\n path: null | string | undefined;\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (let i = 0; i < ids.length; ++i) {\n res.add(ids[i]!.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (let i = 0; i < entries.length; ++i) {\n const [id, envelope] = entries[i]!;\n\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n const res = [...idOrIds];\n res.sort();\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Inits/updates, and returns the heap.\n */\nfunction useHeap<\n DataT,\n IdT extends number | string,\n>(\n ids: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n gs: GlobalState<unknown>,\n): HeapT<DataT, IdT> {\n const ref = useRef<HeapT<DataT, IdT>>();\n\n let heap = ref.current;\n\n if (heap) {\n // Update.\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n heap.globalState = gs;\n } else {\n // Initialization.\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const heap2 = ref.current!;\n\n const localLoader = customLoader || heap2.loader;\n if (!localLoader || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap2.ids.length; ++i) {\n const id = heap2.ids[i]!;\n const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;\n\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap2.globalState,\n );\n }\n };\n heap = {\n globalState: gs,\n ids,\n path,\n loader,\n reload,\n reloadSingle: (customLoader) => ref.current!.reload(\n customLoader && ((id, ...args) => customLoader(...args)),\n ),\n };\n ref.current = heap;\n }\n\n return heap;\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n const heap = useHeap(ids, path, loader, globalState);\n\n // Server-side logic.\n if (globalState.ssrContext && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\n );\n }\n }\n\n // Client-side logic.\n } else {\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n gcOnWithhold(ids, path, globalState);\n return () => gcOnRelease(ids, path, globalState, garbageCollectAge);\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\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 (async () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, { [id: string]: AsyncDataEnvelopeT<DataT> }\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n const e = localState[idOrIds];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading: !!e?.operationId,\n reload: heap.reloadSingle!,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: heap.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const e = localState[id];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAGA,IAAAE,oBAAA,GAAAF,OAAA;AAEA,IAAAG,aAAA,GAAAH,OAAA;AAYA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAxBA;AACA;AACA;;AAkFA;AACA;AACA;AACA;AACA;AACA;AACA,SAASO,YAAYA,CACnBC,GAAU,EACVC,IAA+B,EAC/BC,EAAwB,EACxB;EACA,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IACF,CAAC;EACH;EAEA,MAAMb,GAAuC,GAAG;IAC9CwE,KAAK,EAAE,CAAC,CAAwC;IAChDD,OAAO,EAAE,KAAK;IACdvC,MAAM,EAAEH,IAAI,CAACG,MAAM;IACnBnB,SAAS,EAAE4D,MAAM,CAACC;EACpB,CAAC;EAED,KAAK,IAAIlF,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGL,GAAG,CAACM,MAAM,EAAE,EAAED,CAAC,EAAE;IACnC,MAAME,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,MAAM8E,CAAC,GAAGF,UAAU,CAAC1E,EAAE,CAAC;IACxB,MAAM6E,OAAO,GAAG,CAAC,CAACD,CAAC,EAAElB,WAAW;IAChC,MAAMvC,SAAS,GAAGyD,CAAC,EAAEzD,SAAS,IAAI,CAAC;IAEnCb,GAAG,CAACwE,KAAK,CAAC9E,EAAE,CAAC,GAAG;MACdgE,IAAI,EAAEb,MAAM,GAAGpC,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,GAAIyD,CAAC,EAAEZ,IAAI,IAAI,IAAK;MAChEa,OAAO;MACP1D;IACF,CAAC;IACDb,GAAG,CAACuE,OAAO,KAAKA,OAAO;IACvB,IAAIvE,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAA2E,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEclC,kBAAkB","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","gcOnWithhold","ids","path","gs","collection","get","i","length","id","envelope","numRefs","newAsyncDataEnvelope","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","isDebugMode","console","log","normalizeIds","idOrIds","Array","isArray","sort","useHeap","loader","ref","useRef","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","load","oldData","meta","reloadSingle","args","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","noSSR","operationId","uuid","state","initialValue","pending","push","data","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","charAt","dropDependencies","old","localState","useGlobalState","e","loading","items","Number","MAX_VALUE","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = { [id in IdT]?: AsyncDataEnvelopeT<DataT> };\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> =\n (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: {\n [id in IdT]: CollectionItemT<DataT>;\n }\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype HeapT<\n DataT,\n IdT extends number | string,\n> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState: GlobalState<unknown>;\n ids: IdT[];\n path: null | string | undefined;\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (let i = 0; i < ids.length; ++i) {\n res.add(ids[i]!.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (let i = 0; i < entries.length; ++i) {\n const [id, envelope] = entries[i]!;\n\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n const res = [...idOrIds];\n res.sort();\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Inits/updates, and returns the heap.\n */\nfunction useHeap<\n DataT,\n IdT extends number | string,\n>(\n ids: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n gs: GlobalState<unknown>,\n): HeapT<DataT, IdT> {\n const ref = useRef<HeapT<DataT, IdT>>(undefined);\n\n let heap = ref.current;\n\n if (heap) {\n // Update.\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n heap.globalState = gs;\n } else {\n // Initialization.\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const heap2 = ref.current!;\n\n const localLoader = customLoader || heap2.loader;\n if (!localLoader || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap2.ids.length; ++i) {\n const id = heap2.ids[i]!;\n const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;\n\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap2.globalState,\n );\n }\n };\n heap = {\n globalState: gs,\n ids,\n path,\n loader,\n reload,\n reloadSingle: (customLoader) => ref.current!.reload(\n customLoader && ((id, ...args) => customLoader(...args)),\n ),\n };\n ref.current = heap;\n }\n\n return heap;\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n const heap = useHeap(ids, path, loader, globalState);\n\n // Server-side logic.\n if (globalState.ssrContext && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\n );\n }\n }\n\n // Client-side logic.\n } else {\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n gcOnWithhold(ids, path, globalState);\n return () => gcOnRelease(ids, path, globalState, garbageCollectAge);\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\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 (async () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, { [id: string]: AsyncDataEnvelopeT<DataT> }\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n const e = localState[idOrIds];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading: !!e?.operationId,\n reload: heap.reloadSingle!,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: heap.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const e = localState[id];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>\n | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAGA,I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+70,7 @@ var _utils = require("./utils");
70
70
 
71
71
  function useGlobalState(path, initialValue) {
72
72
  const globalState = (0, _GlobalStateProvider.getGlobalState)();
73
- const ref = (0, _react.useRef)();
73
+ const ref = (0, _react.useRef)(undefined);
74
74
  let rc;
75
75
  if (!ref.current) {
76
76
  const emitter = new _jsUtils.Emitter();
@@ -1 +1 @@
1
- {"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","rc","current","emitter","Emitter","setter","value","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","useSyncExternalStore","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAVA;;AAqCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AASA;;AAGA;;AAiBA,SAASK,cAAcA,CACrBC,IAA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,CAAAC,OAAA,GAEcvC,cAAc","ignoreList":[]}
1
+ {"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","undefined","rc","current","emitter","Emitter","setter","value","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","useSyncExternalStore","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>(undefined);\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAQA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAjBA;;AA4CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AASA;;AAGA;;AAiBA,SAASK,cAAcA,CACrBC,IAAoB,EACpBC,YAA2C,EAClB;EACzB,MAAMC,WAAW,GAAG,IAAAC,mCAAc,EAAC,CAAC;EAEpC,MAAMC,GAAG,GAAG,IAAAC,aAAM,EAAiBC,SAAS,CAAC;E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ACR,EAAE,CAAEP,IAAI,CAAC;QAC3C,IAAI0B,KAAK,KAAKnB,EAAE,CAAEmB,KAAK,EAAEnB,EAAE,CAAEE,OAAO,CAACkB,IAAI,CAAC,CAAC;MAC7C;IACF,CAAC;EACH;EACApB,EAAE,GAAGH,GAAG,CAACI,OAAQ;EAEjBD,EAAE,CAACL,WAAW,GAAGA,WAAW;EAC5BK,EAAE,CAACP,IAAI,GAAGA,IAAI;EAEdO,EAAE,CAACmB,KAAK,GAAG,IAAAM,2BAAoB,EAC7BzB,EAAE,CAACqB,SAAS,EACZ,MAAMrB,EAAE,CAAEL,WAAW,CAACa,GAAG,CAAkBR,EAAE,CAAEP,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EAEtE,MAAMM,EAAE,CAAEL,WAAW,CAACa,GAAG,CACvBR,EAAE,CAAEP,IAAI,EACR;IAAEC,YAAY;IAAEgC,YAAY,EAAE;EAAK,CACrC,CACF,CAAC;EAED,IAAAC,gBAAS,EAAC,MAAM;IACd,MAAM;MAAEH;IAAQ,CAAC,GAAG3B,GAAG,CAACI,OAAQ;IAChCN,WAAW,CAACiC,KAAK,CAACJ,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAM7B,WAAW,CAACkC,OAAO,CAACL,OAAO,CAAC;EAC3C,CAAC,EAAE,CAAC7B,WAAW,CAAC,CAAC;EAEjB,IAAAgC,gBAAS,EAAC,MAAM;IACd9B,GAAG,CAACI,OAAO,CAAEuB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAAC/B,IAAI,CAAC,CAAC;EAEV,OAAO,CAACO,EAAE,CAACmB,KAAK,EAAEnB,EAAE,CAACI,MAAM,CAAC;AAC9B;AAAC,IAAA0B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcxC,cAAc","ignoreList":[]}
@@ -1,8 +1,8 @@
1
1
  import { isFunction } from 'lodash';
2
- import { createContext, useContext, useRef } from 'react';
2
+ import { createContext, use, useRef } from 'react';
3
3
  import GlobalState from "./GlobalState";
4
4
  import { jsx as _jsx } from "react/jsx-runtime";
5
- const context = /*#__PURE__*/createContext(null);
5
+ const Context = /*#__PURE__*/createContext(null);
6
6
 
7
7
  /**
8
8
  * Gets {@link GlobalState} instance from the context. In most cases
@@ -11,14 +11,7 @@ const context = /*#__PURE__*/createContext(null);
11
11
  * @return
12
12
  */
13
13
  export function getGlobalState() {
14
- // Here Rules of Hooks are violated because "getGlobalState()" does not follow
15
- // convention that hook names should start with use... This is intentional in
16
- // our case, as getGlobalState() hook is intended for advance scenarious,
17
- // while the normal interaction with the global state should happen via
18
- // another hook, useGlobalState().
19
- /* eslint-disable react-hooks/rules-of-hooks */
20
- const globalState = useContext(context);
21
- /* eslint-enable react-hooks/rules-of-hooks */
14
+ const globalState = use(Context);
22
15
  if (!globalState) throw new Error('Missing GlobalStateProvider');
23
16
  return globalState;
24
17
  }
@@ -65,24 +58,23 @@ const GlobalStateProvider = _ref => {
65
58
  children,
66
59
  ...rest
67
60
  } = _ref;
68
- const state = useRef();
69
- if (!state.current) {
70
- // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
71
- // graceful compatibility with JavaScript - if "undefined" stateProxy value
72
- // is given, we want to follow the second branch, which creates a new
73
- // GlobalState with whatever intiialState given.
74
- if ('stateProxy' in rest && rest.stateProxy) {
75
- if (rest.stateProxy === true) state.current = getGlobalState();else state.current = rest.stateProxy;
76
- } else {
61
+ const localStateRef = useRef(undefined);
62
+ let state;
63
+ if ('stateProxy' in rest && rest.stateProxy) {
64
+ localStateRef.current = undefined;
65
+ state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;
66
+ } else {
67
+ if (!localStateRef.current) {
77
68
  const {
78
69
  initialState,
79
70
  ssrContext
80
71
  } = rest;
81
- state.current = new GlobalState(isFunction(initialState) ? initialState() : initialState, ssrContext);
72
+ localStateRef.current = new GlobalState(isFunction(initialState) ? initialState() : initialState, ssrContext);
82
73
  }
74
+ state = localStateRef.current;
83
75
  }
84
- return /*#__PURE__*/_jsx(context.Provider, {
85
- value: state.current,
76
+ return /*#__PURE__*/_jsx(Context, {
77
+ value: state,
86
78
  children: children
87
79
  });
88
80
  };
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","useContext","useRef","GlobalState","jsx","_jsx","context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","state","current","stateProxy","initialState","Provider","value"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>) => {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n};\n\nexport default GlobalStateProvider;\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,UAAU,EACVC,MAAM,QACD,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,UAAU,CAACK,OAAO,CAAC;EACvC;EACA,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASE,aAAaA,CAAA,EAIF;EAAA,IADzBC,sBAAsB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAE7B,MAAM;IAAEG;EAAW,CAAC,GAAGR,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACQ,UAAU,IAAIJ,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOM,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGC,IAAA,IAG+C;EAAA,IAAzE;IAAEC,QAAQ;IAAE,GAAGC;EAAoD,CAAC,GAAAF,IAAA;EACpE,MAAMG,KAAK,GAAGlB,MAAM,CAAmC,CAAC;EACxD,IAAI,CAACkB,KAAK,CAACC,OAAO,EAAE;IAClB;IACA;IACA;IACA;IACA,IAAI,YAAY,IAAIF,IAAI,IAAIA,IAAI,CAACG,UAAU,EAAE;MAC3C,IAAIH,IAAI,CAACG,UAAU,KAAK,IAAI,EAAEF,KAAK,CAACC,OAAO,GAAGd,cAAc,CAAC,CAAC,CAAC,KAC1Da,KAAK,CAACC,OAAO,GAAGF,IAAI,CAACG,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAER;MAAW,CAAC,GAAGI,IAA0C;MAE/EC,KAAK,CAACC,OAAO,GAAG,IAAIlB,WAAW,CAC7BJ,UAAU,CAACwB,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACEV,IAAA,CAACC,OAAO,CAACkB,QAAQ;IAACC,KAAK,EAAEL,KAAK,CAACC,OAAQ;IAAAH,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB,CAAC;AAED,eAAeF,mBAAmB","ignoreList":[]}
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","use","useRef","GlobalState","jsx","_jsx","Context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","localStateRef","state","stateProxy","current","initialState","value"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n use,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst Context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>) => {\n type GST = GlobalState<StateT, SsrContextT>;\n const localStateRef = useRef<GST>(undefined);\n let state: GST;\n if ('stateProxy' in rest && rest.stateProxy) {\n localStateRef.current = undefined;\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else {\n if (!localStateRef.current) {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n localStateRef.current = new GlobalState(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n state = localStateRef.current;\n }\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,GAAG,EACHC,MAAM,QACD,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC,MAAMC,WAAW,GAAGP,GAAG,CAACK,OAAO,CAAC;EAChC,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASE,aAAaA,CAAA,EAIF;EAAA,IADzBC,sBAAsB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAE7B,MAAM;IAAEG;EAAW,CAAC,GAAGR,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACQ,UAAU,IAAIJ,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOM,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGC,IAAA,IAG+C;EAAA,IAAzE;IAAEC,QAAQ;IAAE,GAAGC;EAAoD,CAAC,GAAAF,IAAA;EAEpE,MAAMG,aAAa,GAAGlB,MAAM,CAAMY,SAAS,CAAC;EAC5C,IAAIO,KAAU;EACd,IAAI,YAAY,IAAIF,IAAI,IAAIA,IAAI,CAACG,UAAU,EAAE;IAC3CF,aAAa,CAACG,OAAO,GAAGT,SAAS;IACjCO,KAAK,GAAGF,IAAI,CAACG,UAAU,KAAK,IAAI,GAAGf,cAAc,CAAC,CAAC,GAAGY,IAAI,CAACG,UAAU;EACvE,CAAC,MAAM;IACL,IAAI,CAACF,aAAa,CAACG,OAAO,EAAE;MAC1B,MAAM;QAAEC,YAAY;QAAET;MAAW,CAAC,GAAGI,IAA0C;MAC/EC,aAAa,CAACG,OAAO,GAAG,IAAIpB,WAAW,CACrCJ,UAAU,CAACyB,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDT,UACF,CAAC;IACH;IACAM,KAAK,GAAGD,aAAa,CAACG,OAAO;EAC/B;EACA,oBAAOlB,IAAA,CAACC,OAAO;IAACmB,KAAK,EAAEJ,KAAM;IAAAH,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAED,eAAeF,mBAAmB","ignoreList":[]}
@@ -85,7 +85,7 @@ function normalizeIds(idOrIds) {
85
85
  * Inits/updates, and returns the heap.
86
86
  */
87
87
  function useHeap(ids, path, loader, gs) {
88
- const ref = useRef();
88
+ const ref = useRef(undefined);
89
89
  let heap = ref.current;
90
90
  if (heap) {
91
91
  // Update.
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","hash","isDebugMode","gcOnWithhold","ids","path","gs","collection","get","i","length","id","envelope","numRefs","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","console","log","normalizeIds","idOrIds","Array","isArray","sort","useHeap","loader","ref","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","oldData","meta","reloadSingle","_len","arguments","args","_key","useAsyncCollection","_options$maxage","_options$refreshAge","_options$garbageColle","options","undefined","maxage","refreshAge","garbageCollectAge","ssrContext","noSSR","operationId","state","initialValue","pending","push","_len2","_key2","data","idsHash","_state2$timestamp","state2","deps","hasChangedDependencies","charAt","_state2$timestamp2","dropDependencies","old","_len3","_key3","localState","_e$timestamp","_e$data","e","loading","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = { [id in IdT]?: AsyncDataEnvelopeT<DataT> };\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> =\n (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: {\n [id in IdT]: CollectionItemT<DataT>;\n }\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype HeapT<\n DataT,\n IdT extends number | string,\n> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState: GlobalState<unknown>;\n ids: IdT[];\n path: null | string | undefined;\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (let i = 0; i < ids.length; ++i) {\n res.add(ids[i]!.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (let i = 0; i < entries.length; ++i) {\n const [id, envelope] = entries[i]!;\n\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n const res = [...idOrIds];\n res.sort();\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Inits/updates, and returns the heap.\n */\nfunction useHeap<\n DataT,\n IdT extends number | string,\n>(\n ids: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n gs: GlobalState<unknown>,\n): HeapT<DataT, IdT> {\n const ref = useRef<HeapT<DataT, IdT>>();\n\n let heap = ref.current;\n\n if (heap) {\n // Update.\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n heap.globalState = gs;\n } else {\n // Initialization.\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const heap2 = ref.current!;\n\n const localLoader = customLoader || heap2.loader;\n if (!localLoader || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap2.ids.length; ++i) {\n const id = heap2.ids[i]!;\n const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;\n\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap2.globalState,\n );\n }\n };\n heap = {\n globalState: gs,\n ids,\n path,\n loader,\n reload,\n reloadSingle: (customLoader) => ref.current!.reload(\n customLoader && ((id, ...args) => customLoader(...args)),\n ),\n };\n ref.current = heap;\n }\n\n return heap;\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n const heap = useHeap(ids, path, loader, globalState);\n\n // Server-side logic.\n if (globalState.ssrContext && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\n );\n }\n }\n\n // Client-side logic.\n } else {\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n gcOnWithhold(ids, path, globalState);\n return () => gcOnRelease(ids, path, globalState, garbageCollectAge);\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\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 (async () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, { [id: string]: AsyncDataEnvelopeT<DataT> }\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n const e = localState[idOrIds];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading: !!e?.operationId,\n reload: heap.reloadSingle!,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: heap.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const e = localState[id];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAGjC,SAASC,cAAc;AAEvB,SAOEC,cAAc,EACdC,IAAI,EACJC,oBAAoB;AAGtB,OAAOC,cAAc;AAErB,SAIEC,IAAI,EACJC,WAAW;AAuDb;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,YAAYA,CACnBC,GAAU,EACVC,IAA+B,EAC/BC,EAAwB,EACxB;EACA,MAAMC,UAAU,GAAG;IAAE,GAAGD,EAAE,CAACE,GAAG,CAA2BH,IAAI;EAAE,CAAC;EAEhE,KAAK,IAAII,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGL,GAAG,CAACM,MAAM,EAAE,EAAED,CAAC,EAAE;IACnC,MAAME,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,IAAIG,QAAQ,GAAGL,UAAU,CAACI,EAAE,CAAC;IAC7B,IAAIC,QAAQ,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A;IACnC,MAAMvF,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,MAAMmF,CAAC,GAAGH,UAAU,CAAC9E,EAAE,CAAC;IACxB,MAAMkF,OAAO,GAAG,CAAC,EAACD,CAAC,aAADA,CAAC,eAADA,CAAC,CAAEtB,WAAW;IAChC,MAAMzC,SAAS,IAAAoE,aAAA,GAAGL,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAE/D,SAAS,cAAAoE,aAAA,cAAAA,aAAA,GAAI,CAAC;IAEnCjF,GAAG,CAAC8E,KAAK,CAACnF,EAAE,CAAC,GAAG;MACdkE,IAAI,EAAEZ,MAAM,GAAGxC,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,IAAAqE,QAAA,GAAIN,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAEf,IAAI,cAAAqB,QAAA,cAAAA,QAAA,GAAI,IAAK;MAChEL,OAAO;MACPhE;IACF,CAAC;IACDb,GAAG,CAAC6E,OAAO,KAAX7E,GAAG,CAAC6E,OAAO,GAAKA,OAAO;IACvB,IAAI7E,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAe2C,kBAAkB","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","hash","isDebugMode","gcOnWithhold","ids","path","gs","collection","get","i","length","id","envelope","numRefs","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","console","log","normalizeIds","idOrIds","Array","isArray","sort","useHeap","loader","ref","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","oldData","meta","reloadSingle","_len","arguments","args","_key","useAsyncCollection","_options$maxage","_options$refreshAge","_options$garbageColle","options","maxage","refreshAge","garbageCollectAge","ssrContext","noSSR","operationId","state","initialValue","pending","push","_len2","_key2","data","idsHash","_state2$timestamp","state2","deps","hasChangedDependencies","charAt","_state2$timestamp2","dropDependencies","old","_len3","_key3","localState","_e$timestamp","_e$data","e","loading","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = { [id in IdT]?: AsyncDataEnvelopeT<DataT> };\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> =\n (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: {\n [id in IdT]: CollectionItemT<DataT>;\n }\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype HeapT<\n DataT,\n IdT extends number | string,\n> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState: GlobalState<unknown>;\n ids: IdT[];\n path: null | string | undefined;\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (let i = 0; i < ids.length; ++i) {\n res.add(ids[i]!.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (let i = 0; i < entries.length; ++i) {\n const [id, envelope] = entries[i]!;\n\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n const res = [...idOrIds];\n res.sort();\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Inits/updates, and returns the heap.\n */\nfunction useHeap<\n DataT,\n IdT extends number | string,\n>(\n ids: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n gs: GlobalState<unknown>,\n): HeapT<DataT, IdT> {\n const ref = useRef<HeapT<DataT, IdT>>(undefined);\n\n let heap = ref.current;\n\n if (heap) {\n // Update.\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n heap.globalState = gs;\n } else {\n // Initialization.\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const heap2 = ref.current!;\n\n const localLoader = customLoader || heap2.loader;\n if (!localLoader || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap2.ids.length; ++i) {\n const id = heap2.ids[i]!;\n const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;\n\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap2.globalState,\n );\n }\n };\n heap = {\n globalState: gs,\n ids,\n path,\n loader,\n reload,\n reloadSingle: (customLoader) => ref.current!.reload(\n customLoader && ((id, ...args) => customLoader(...args)),\n ),\n };\n ref.current = heap;\n }\n\n return heap;\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n const heap = useHeap(ids, path, loader, globalState);\n\n // Server-side logic.\n if (globalState.ssrContext && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\n );\n }\n }\n\n // Client-side logic.\n } else {\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n gcOnWithhold(ids, path, globalState);\n return () => gcOnRelease(ids, path, globalState, garbageCollectAge);\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\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 (async () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, { [id: string]: AsyncDataEnvelopeT<DataT> }\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n const e = localState[idOrIds];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading: !!e?.operationId,\n reload: heap.reloadSingle!,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: heap.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const e = localState[id];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>\n | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAGjC,SAASC,cAAc;AAEvB,SAOEC,cAAc,EACdC,IAAI,EACJ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AAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAe4C,kBAAkB","ignoreList":[]}
@@ -65,7 +65,7 @@ import { cloneDeepForLog, isDebugMode } from "./utils";
65
65
 
66
66
  function useGlobalState(path, initialValue) {
67
67
  const globalState = getGlobalState();
68
- const ref = useRef();
68
+ const ref = useRef(undefined);
69
69
  let rc;
70
70
  if (!ref.current) {
71
71
  const emitter = new Emitter();
@@ -1 +1 @@
1
- {"version":3,"file":"useGlobalState.js","names":["isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","cloneDeepForLog","isDebugMode","useGlobalState","path","initialValue","globalState","ref","rc","current","emitter","setter","value","newState","get","process","env","NODE_ENV","_rc$path","console","groupCollapsed","log","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":"AAAA;;AAEA,SAASA,UAAU,QAAQ,QAAQ;AACnC,SAASC,SAAS,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,OAAO;AAE/D,SAASC,OAAO,QAAQ,sBAAsB;AAG9C,SAASC,cAAc;AAEvB,SAOEC,eAAe,EACfC,WAAW;;AAmBb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AASA;;AAGA;;AAiBA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EA,eAAeR,cAAc","ignoreList":[]}
1
+ {"version":3,"file":"useGlobalState.js","names":["isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","cloneDeepForLog","isDebugMode","useGlobalState","path","initialValue","globalState","ref","undefined","rc","current","emitter","setter","value","newState","get","process","env","NODE_ENV","_rc$path","console","groupCollapsed","log","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>(undefined);\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":"AAAA;;AAEA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAGEC,SAAS,EACTC,MAAM,EACNC,oBAAoB,QACf,OAAO;AAEd,SAASC,OAAO,QAAQ,sBAAsB;AAG9C,SAASC,cAAc;AAEvB,SAOEC,eAAe,EACfC,WAAW;;AAmBb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AASA;;AAGA;;AAiBA,SAASC,cAAcA,CACrBC,IAAoB,EACpBC,YAA2C,EAClB;EACzB,MAAMC,WAAW,GAAGN,cAAc,CAAC,CAAC;EAEpC,MAAMO,GAAG,GAAGV,MAAM,CAAiBW,SAAS,CAAC;EAE7C,IAAIC,EAAkB;EACtB,IAAI,CAACF,GAAG,CAACG,OAAO,EAAE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AC;QAC3C,IAAIqB,KAAK,KAAKhB,EAAE,CAAEgB,KAAK,EAAEhB,EAAE,CAAEE,OAAO,CAACe,IAAI,CAAC,CAAC;MAC7C;IACF,CAAC;EACH;EACAjB,EAAE,GAAGF,GAAG,CAACG,OAAQ;EAEjBD,EAAE,CAACH,WAAW,GAAGA,WAAW;EAC5BG,EAAE,CAACL,IAAI,GAAGA,IAAI;EAEdK,EAAE,CAACgB,KAAK,GAAG3B,oBAAoB,CAC7BW,EAAE,CAACkB,SAAS,EACZ,MAAMlB,EAAE,CAAEH,WAAW,CAACS,GAAG,CAAkBN,EAAE,CAAEL,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EAEtE,MAAMI,EAAE,CAAEH,WAAW,CAACS,GAAG,CACvBN,EAAE,CAAEL,IAAI,EACR;IAAEC,YAAY;IAAE0B,YAAY,EAAE;EAAK,CACrC,CACF,CAAC;EAEDnC,SAAS,CAAC,MAAM;IACd,MAAM;MAAEkC;IAAQ,CAAC,GAAGvB,GAAG,CAACG,OAAQ;IAChCJ,WAAW,CAAC0B,KAAK,CAACF,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAMxB,WAAW,CAAC2B,OAAO,CAACH,OAAO,CAAC;EAC3C,CAAC,EAAE,CAACxB,WAAW,CAAC,CAAC;EAEjBV,SAAS,CAAC,MAAM;IACdW,GAAG,CAACG,OAAO,CAAEoB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAAC1B,IAAI,CAAC,CAAC;EAEV,OAAO,CAACK,EAAE,CAACgB,KAAK,EAAEhB,EAAE,CAACG,MAAM,CAAC;AAC9B;AAEA,eAAeT,cAAc","ignoreList":[]}
@@ -33,10 +33,12 @@ declare function useAsyncCollection<StateT, PathT extends null | string | undefi
33
33
  declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
34
34
  declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends number | string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataT, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
35
35
  declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT[], path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
36
+ declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends number | string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT | IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataT, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;
36
37
  export default useAsyncCollection;
37
38
  export interface UseAsyncCollectionI<StateT> {
38
39
  <PathT extends null | string | undefined, IdT extends number | string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
39
40
  <Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
40
41
  <PathT extends null | string | undefined, IdT extends number | string>(id: IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;
41
42
  <Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT[], path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
43
+ <PathT extends null | string | undefined, IdT extends number | string>(id: IdT | IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>> | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;
42
44
  }
@@ -1,5 +1,6 @@
1
+ import { type Dispatch, type SetStateAction } from 'react';
1
2
  import { type ForceT, type LockT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
2
- export type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;
3
+ export type SetterT<T> = Dispatch<SetStateAction<T>>;
3
4
  export type UseGlobalStateResT<T> = [T, SetterT<T>];
4
5
  /**
5
6
  * The primary hook for interacting with the global state, modeled after
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.17.5",
3
+ "version": "0.18.1",
4
4
  "description": "Hook-based global state for React",
5
5
  "main": "./build/common/index.js",
6
6
  "react-native": "src/index.ts",
@@ -44,28 +44,28 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@babel/runtime": "^7.26.0",
47
- "@dr.pogodin/js-utils": "^0.0.12",
47
+ "@dr.pogodin/js-utils": "^0.0.13",
48
48
  "@types/lodash": "^4.17.13",
49
49
  "lodash": "^4.17.21",
50
50
  "uuid": "^11.0.3"
51
51
  },
52
52
  "devDependencies": {
53
- "@babel/cli": "^7.25.9",
53
+ "@babel/cli": "^7.26.4",
54
54
  "@babel/core": "^7.26.0",
55
55
  "@babel/eslint-parser": "^7.25.9",
56
56
  "@babel/eslint-plugin": "^7.25.9",
57
57
  "@babel/node": "^7.26.0",
58
58
  "@babel/plugin-transform-runtime": "^7.25.9",
59
59
  "@babel/preset-env": "^7.26.0",
60
- "@babel/preset-react": "^7.25.9",
60
+ "@babel/preset-react": "^7.26.3",
61
61
  "@babel/preset-typescript": "^7.26.0",
62
62
  "@testing-library/dom": "^10.4.0",
63
- "@testing-library/react": "^16.0.1",
63
+ "@testing-library/react": "^16.1.0",
64
64
  "@tsconfig/recommended": "^1.0.8",
65
65
  "@types/jest": "^29.5.14",
66
66
  "@types/pretty": "^2.0.3",
67
- "@types/react": "^18.3.12",
68
- "@types/react-dom": "^18.3.1",
67
+ "@types/react": "^19.0.2",
68
+ "@types/react-dom": "^19.0.2",
69
69
  "babel-jest": "^29.7.0",
70
70
  "babel-plugin-module-resolver": "^5.0.2",
71
71
  "eslint": "^8.57.1",
@@ -73,20 +73,20 @@
73
73
  "eslint-config-airbnb-typescript": "^18.0.0",
74
74
  "eslint-import-resolver-babel-module": "^5.3.2",
75
75
  "eslint-plugin-import": "^2.31.0",
76
- "eslint-plugin-jest": "^28.9.0",
76
+ "eslint-plugin-jest": "^28.10.0",
77
77
  "eslint-plugin-jsx-a11y": "^6.10.2",
78
- "eslint-plugin-react": "^7.37.2",
78
+ "eslint-plugin-react": "^7.37.3",
79
79
  "eslint-plugin-react-hooks": "^4.6.2",
80
80
  "jest": "^29.7.0",
81
81
  "jest-environment-jsdom": "^29.7.0",
82
82
  "mockdate": "^3.0.5",
83
83
  "rimraf": "^6.0.1",
84
- "tstyche": "^3.0.0",
85
- "typescript": "^5.6.3",
86
- "typescript-eslint": "^8.15.0"
84
+ "tstyche": "^3.3.1",
85
+ "typescript": "^5.7.2",
86
+ "typescript-eslint": "^8.19.0"
87
87
  },
88
88
  "peerDependencies": {
89
- "react": "^18.3.1",
90
- "react-dom": "^18.3.1"
89
+ "react": "^19.0.0",
90
+ "react-dom": "^19.0.0"
91
91
  }
92
92
  }
@@ -3,7 +3,7 @@ import { isFunction } from 'lodash';
3
3
  import {
4
4
  type ReactNode,
5
5
  createContext,
6
- useContext,
6
+ use,
7
7
  useRef,
8
8
  } from 'react';
9
9
 
@@ -12,7 +12,7 @@ import SsrContext from './SsrContext';
12
12
 
13
13
  import { type ValueOrInitializerT } from './utils';
14
14
 
15
- const context = createContext<GlobalState<unknown> | null>(null);
15
+ const Context = createContext<GlobalState<unknown> | null>(null);
16
16
 
17
17
  /**
18
18
  * Gets {@link GlobalState} instance from the context. In most cases
@@ -24,14 +24,7 @@ export function getGlobalState<
24
24
  StateT,
25
25
  SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
26
26
  >(): GlobalState<StateT, SsrContextT> {
27
- // Here Rules of Hooks are violated because "getGlobalState()" does not follow
28
- // convention that hook names should start with use... This is intentional in
29
- // our case, as getGlobalState() hook is intended for advance scenarious,
30
- // while the normal interaction with the global state should happen via
31
- // another hook, useGlobalState().
32
- /* eslint-disable react-hooks/rules-of-hooks */
33
- const globalState = useContext(context);
34
- /* eslint-enable react-hooks/rules-of-hooks */
27
+ const globalState = use(Context);
35
28
  if (!globalState) throw new Error('Missing GlobalStateProvider');
36
29
  return globalState as GlobalState<StateT, SsrContextT>;
37
30
  }
@@ -93,29 +86,23 @@ const GlobalStateProvider = <
93
86
  StateT,
94
87
  SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
95
88
  >({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>) => {
96
- const state = useRef<GlobalState<StateT, SsrContextT>>();
97
- if (!state.current) {
98
- // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
99
- // graceful compatibility with JavaScript - if "undefined" stateProxy value
100
- // is given, we want to follow the second branch, which creates a new
101
- // GlobalState with whatever intiialState given.
102
- if ('stateProxy' in rest && rest.stateProxy) {
103
- if (rest.stateProxy === true) state.current = getGlobalState();
104
- else state.current = rest.stateProxy;
105
- } else {
89
+ type GST = GlobalState<StateT, SsrContextT>;
90
+ const localStateRef = useRef<GST>(undefined);
91
+ let state: GST;
92
+ if ('stateProxy' in rest && rest.stateProxy) {
93
+ localStateRef.current = undefined;
94
+ state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;
95
+ } else {
96
+ if (!localStateRef.current) {
106
97
  const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;
107
-
108
- state.current = new GlobalState<StateT, SsrContextT>(
98
+ localStateRef.current = new GlobalState(
109
99
  isFunction(initialState) ? initialState() : initialState,
110
100
  ssrContext,
111
101
  );
112
102
  }
103
+ state = localStateRef.current;
113
104
  }
114
- return (
115
- <context.Provider value={state.current}>
116
- {children}
117
- </context.Provider>
118
- );
105
+ return <Context value={state}>{children}</Context>;
119
106
  };
120
107
 
121
108
  export default GlobalStateProvider;
@@ -185,7 +185,7 @@ function useHeap<
185
185
  loader: AsyncCollectionLoaderT<DataT, IdT>,
186
186
  gs: GlobalState<unknown>,
187
187
  ): HeapT<DataT, IdT> {
188
- const ref = useRef<HeapT<DataT, IdT>>();
188
+ const ref = useRef<HeapT<DataT, IdT>>(undefined);
189
189
 
190
190
  let heap = ref.current;
191
191
 
@@ -290,6 +290,20 @@ function useAsyncCollection<
290
290
  options?: UseAsyncDataOptionsT,
291
291
  ): UseAsyncCollectionResT<DataT, IdT>;
292
292
 
293
+ function useAsyncCollection<
294
+ StateT,
295
+ PathT extends null | string | undefined,
296
+ IdT extends number | string,
297
+
298
+ DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =
299
+ DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,
300
+ >(
301
+ id: IdT | IdT[],
302
+ path: PathT,
303
+ loader: AsyncCollectionLoaderT<DataT, IdT>,
304
+ options?: UseAsyncDataOptionsT,
305
+ ): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;
306
+
293
307
  // TODO: This is largely similar to useAsyncData() logic, just more generic.
294
308
  // Perhaps, a bunch of logic blocks can be split into stand-alone functions,
295
309
  // and reused in both hooks.
@@ -468,4 +482,12 @@ export interface UseAsyncCollectionI<StateT> {
468
482
  loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,
469
483
  options?: UseAsyncDataOptionsT,
470
484
  ): UseAsyncCollectionResT<DataT, IdT>;
485
+
486
+ <PathT extends null | string | undefined, IdT extends number | string>(
487
+ id: IdT | IdT[],
488
+ path: PathT,
489
+ loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,
490
+ options?: UseAsyncDataOptionsT,
491
+ ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>
492
+ | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;
471
493
  }
@@ -1,7 +1,14 @@
1
1
  // Hook for updates of global state.
2
2
 
3
3
  import { isFunction } from 'lodash';
4
- import { useEffect, useRef, useSyncExternalStore } from 'react';
4
+
5
+ import {
6
+ type Dispatch,
7
+ type SetStateAction,
8
+ useEffect,
9
+ useRef,
10
+ useSyncExternalStore,
11
+ } from 'react';
5
12
 
6
13
  import { Emitter } from '@dr.pogodin/js-utils';
7
14
 
@@ -19,7 +26,7 @@ import {
19
26
  isDebugMode,
20
27
  } from './utils';
21
28
 
22
- export type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;
29
+ export type SetterT<T> = Dispatch<SetStateAction<T>>;
23
30
 
24
31
  type ListenerT = () => void;
25
32
 
@@ -121,7 +128,7 @@ function useGlobalState(
121
128
  ): UseGlobalStateResT<any> {
122
129
  const globalState = getGlobalState();
123
130
 
124
- const ref = useRef<GlobalStateRef>();
131
+ const ref = useRef<GlobalStateRef>(undefined);
125
132
 
126
133
  let rc: GlobalStateRef;
127
134
  if (!ref.current) {