@dr.pogodin/react-global-state 0.7.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
1
  import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
2
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
3
3
  import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
4
4
  import _regeneratorRuntime from "@babel/runtime/regenerator";
5
5
 
@@ -157,21 +157,23 @@ export default function useAsyncData(path, loader) {
157
157
  refreshAge = options.refreshAge;
158
158
  if (maxage === undefined) maxage = DEFAULT_MAXAGE;
159
159
  if (refreshAge === undefined) refreshAge = maxage;
160
- if (garbageCollectAge === undefined) garbageCollectAge = maxage;
161
- var globalState = getGlobalState();
160
+ if (garbageCollectAge === undefined) garbageCollectAge = maxage; // Note: here we can't depend on useGlobalState() to init the initial value,
161
+ // because that way we'll have issues with SSR (see details below).
162
162
 
163
- var _useGlobalState = useGlobalState(path, {
164
- data: null,
165
- numRefs: 0,
166
- operationId: '',
167
- timestamp: 0
168
- }),
169
- _useGlobalState2 = _slicedToArray(_useGlobalState, 1),
170
- localState = _useGlobalState2[0];
163
+ var globalState = getGlobalState();
164
+ var state = globalState.get(path);
165
+
166
+ if (state === undefined) {
167
+ state = {
168
+ data: null,
169
+ numRefs: 0,
170
+ operationId: '',
171
+ timestamp: 0
172
+ };
173
+ globalState.set(path, state);
174
+ }
171
175
 
172
176
  if (globalState.ssrContext && !options.noSSR) {
173
- var state = globalState.get(path);
174
-
175
177
  if (!state.timestamp && !state.operationId) {
176
178
  globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
177
179
  }
@@ -191,21 +193,21 @@ export default function useAsyncData(path, loader) {
191
193
  var numRefs = globalState.get(numRefsPath);
192
194
  globalState.set(numRefsPath, numRefs + 1);
193
195
  return function () {
194
- var state = globalState.get(path);
196
+ var state2 = globalState.get(path);
195
197
 
196
- if (state.numRefs === 1 && garbageCollectAge < Date.now() - state.timestamp) {
198
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
197
199
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
198
200
  /* eslint-disable no-console */
199
201
  console.log("ReactGlobalState - useAsyncData garbage collected at path ".concat(path || ''));
200
202
  /* eslint-enable no-console */
201
203
  }
202
204
 
203
- globalState.set(path, _objectSpread(_objectSpread({}, state), {}, {
205
+ globalState.set(path, _objectSpread(_objectSpread({}, state2), {}, {
204
206
  data: null,
205
207
  numRefs: 0,
206
208
  timestamp: 0
207
209
  }));
208
- } else globalState.set(numRefsPath, state.numRefs - 1);
210
+ } else globalState.set(numRefsPath, state2.numRefs - 1);
209
211
  };
210
212
  }, [garbageCollectAge, globalState, path]); // Note: a bunch of Rules of Hooks ignored belows because in our very
211
213
  // special case the otherwise wrong behavior is actually what we need.
@@ -214,10 +216,10 @@ export default function useAsyncData(path, loader) {
214
216
  var loadTriggered = false;
215
217
  useEffect(function () {
216
218
  // eslint-disable-line react-hooks/rules-of-hooks
217
- var state = globalState.get(path);
219
+ var state2 = globalState.get(path);
218
220
 
219
- if (refreshAge < Date.now() - state.timestamp && (!state.operationId || state.operationId.charAt() === 'S')) {
220
- load(path, loader, globalState, state.data);
221
+ if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt() === 'S')) {
222
+ load(path, loader, globalState, state2.data);
221
223
  loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
222
224
  }
223
225
  });
@@ -226,7 +228,16 @@ export default function useAsyncData(path, loader) {
226
228
  // eslint-disable-line react-hooks/rules-of-hooks
227
229
  if (!loadTriggered && deps.length) load(path, loader, globalState);
228
230
  }, deps); // eslint-disable-line react-hooks/exhaustive-deps
229
- }
231
+ } // Note: this subscription to updates of the global state segment must be
232
+ // here, after the possible initialization of the loading operation, to take
233
+ // into effect the resulting loading state. This mostly ensures the correct
234
+ // SSR in the edge case when the loading starts, but times out, and incomplete
235
+ // render has to be served.
236
+
237
+
238
+ var _useGlobalState = useGlobalState(path),
239
+ _useGlobalState2 = _slicedToArray(_useGlobalState, 1),
240
+ localState = _useGlobalState2[0];
230
241
 
231
242
  return {
232
243
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/useAsyncData.js"],"names":["cloneDeep","useEffect","v4","uuid","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationId","operationIdPath","set","get","data","state","groupCollapsed","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","numRefs","localState","ssrContext","noSSR","pending","push","numRefsPath","loadTriggered","charAt","deps","length","loading","Boolean"],"mappings":";;;;;;;;;AAAA;AACA;AACA;AAEA,SAASA,SAAT,QAA0B,QAA1B;AACA,SAASC,SAAT,QAA0B,OAA1B;AACA,SAASC,EAAE,IAAIC,IAAf,QAA2B,MAA3B;AAEA,SAASC,cAAT;AACA,OAAOC,cAAP;AACA,SAASC,WAAT;AAEA,IAAMC,cAAc,GAAG,IAAI,EAAJ,GAAS,IAAhC,C,CAAsC;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;SACeC,I;;;AAsCf;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;AACA;;;;mEAxFA,iBAAoBC,IAApB,EAA0BC,MAA1B,EAAkCC,WAAlC,EAA+CC,OAA/C;AAAA;AAAA;AAAA;AAAA;AAAA;A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KAAK,CAACL,WAAN,CAAkByB,MAAlB,OAA+B,GADrD,CAAJ,EAC+D;AAC7DpC,QAAAA,IAAI,CAACC,IAAD,EAAOC,MAAP,EAAeC,WAAf,EAA4Ba,KAAK,CAACD,IAAlC,CAAJ;AACAoB,QAAAA,aAAa,GAAG,IAAhB,CAF6D,CAEvC;AACvB;AACF,KAPQ,CAAT;AASA,QAAME,IAAI,GAAGd,OAAO,CAACc,IAAR,IAAgB,EAA7B;AACA5C,IAAAA,SAAS,CAAC,YAAM;AAAE;AAChB,UAAI,CAAC0C,aAAD,IAAkBE,IAAI,CAACC,MAA3B,EAAmCtC,IAAI,CAACC,IAAD,EAAOC,MAAP,EAAeC,WAAf,CAAJ;AACpC,KAFQ,EAENkC,IAFM,CAAT,CAtDK,CAwDK;AACX;;AAED,SAAO;AACLtB,IAAAA,IAAI,EAAEU,MAAM,GAAGN,IAAI,CAACC,GAAL,KAAaS,UAAU,CAACX,SAAjC,GAA6C,IAA7C,GAAoDW,UAAU,CAACd,IADhE;AAELwB,IAAAA,OAAO,EAAEC,OAAO,CAACX,UAAU,CAAClB,WAAZ,CAFX;AAGLO,IAAAA,SAAS,EAAEW,UAAU,CAACX;AAHjB,GAAP;AAKD","sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [oldData] Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param {object} [options] Additional options.\n * @param {any[]} [options.deps=[]] An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param {number} [options.refreshAge=maxage] The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) garbageCollectAge = maxage;\n\n const globalState = getGlobalState();\n const [localState] = useGlobalState(path, {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n const state = globalState.get(path);\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state = globalState.get(path);\n if (\n state.numRefs === 1\n && garbageCollectAge < Date.now() - state.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(numRefsPath, state.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state = globalState.get(path);\n if (refreshAge < Date.now() - state.timestamp\n && (!state.operationId || state.operationId.charAt() === 'S')) {\n load(path, loader, globalState, state.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n"],"file":"useAsyncData.js"}
1
+ {"version":3,"sources":["../../src/useAsyncData.js"],"names":["cloneDeep","useEffect","v4","uuid","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationId","operationIdPath","set","get","data","state","groupCollapsed","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","numRefs","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","loading","Boolean"],"mappings":";;;;;;;;;AAAA;AACA;AACA;AAEA,SAASA,SAAT,QAA0B,QAA1B;AACA,SAASC,SAAT,QAA0B,OAA1B;AACA,SAASC,EAAE,IAAIC,IAAf,QAA2B,MAA3B;AAEA,SAASC,cAAT;AACA,OAAOC,cAAP;AACA,SAASC,WAAT;AAEA,IAAMC,cAAc,GAAG,IAAI,EAAJ,GAAS,IAAhC,C,CAAsC;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;SACeC,I;;;AAsCf;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;AACA;;;;mEAxFA,iBAAoBC,IAApB,EAA0BC,MAA1B,EAAkCC,WAAlC,EAA+CC,OAA/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAwDC,YAAAA,UAAxD,2DAAqE,GAArE;;AACE,gBAAIC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IAAyCV,WAAW,EAAxD,EAA4D;AAC1D;AACAW,cAAAA,OAAO,CAACC,GAAR,qEAC8DT,IAAI,IAAI,EADtE;AAGA;AACD;;AACKU,YAAAA,WARR,GAQsBN,UAAU,GAAGV,IAAI,EARvC;AASQiB,YAAAA,eATR,GAS0BX,IAAI,aAAMA,IAAN,oBAA2B,aATzD;AAUEE,YAAAA,WAAW,CAACU,GAAZ,CAAgBD,eA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;AAAE;AAChB,UAAI,CAAC0C,aAAD,IAAkBE,IAAI,CAACC,MAA3B,EAAmCtC,IAAI,CAACC,IAAD,EAAOC,MAAP,EAAeC,WAAf,CAAJ;AACpC,KAFQ,EAENkC,IAFM,CAAT,CAtDK,CAwDK;AACX,GAnFD,CAqFA;AACA;AACA;AACA;AACA;;;AACA,wBAAqBxC,cAAc,CAACI,IAAD,CAAnC;AAAA;AAAA,MAAOsC,UAAP;;AAEA,SAAO;AACLxB,IAAAA,IAAI,EAAEU,MAAM,GAAGN,IAAI,CAACC,GAAL,KAAamB,UAAU,CAACrB,SAAjC,GAA6C,IAA7C,GAAoDqB,UAAU,CAACxB,IADhE;AAELyB,IAAAA,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC5B,WAAZ,CAFX;AAGLO,IAAAA,SAAS,EAAEqB,UAAU,CAACrB;AAHjB,GAAP;AAKD","sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [oldData] Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param {object} [options] Additional options.\n * @param {any[]} [options.deps=[]] An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param {number} [options.refreshAge=maxage] The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) garbageCollectAge = maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n let state = globalState.get(path);\n if (state === undefined) {\n state = {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n globalState.set(path, state);\n }\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state2 = globalState.get(path);\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2 = globalState.get(path);\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt() === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n // Note: this subscription to updates of the global state segment must be\n // here, after the possible initialization of the loading operation, to take\n // into effect the resulting loading state. This mostly ensures the correct\n // SSR in the edge case when the loading starts, but times out, and incomplete\n // render has to be served.\n const [localState] = useGlobalState(path);\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n"],"file":"useAsyncData.js"}
@@ -1,6 +1,6 @@
1
1
  import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
2
2
  // Hook for updates of global state.
3
- import { cloneDeep, isFunction, isUndefined } from 'lodash';
3
+ import { cloneDeep, isFunction } from 'lodash';
4
4
  import { useEffect, useRef, useState } from 'react';
5
5
  import { getGlobalState } from "./GlobalStateProvider";
6
6
  import { isDebugMode } from "./utils";
@@ -59,7 +59,7 @@ export default function useGlobalState(path, initialValue) {
59
59
  var globalState = getGlobalState();
60
60
  var state = globalState.get(path);
61
61
 
62
- if (isUndefined(state) && !isUndefined(initialValue)) {
62
+ if (state === undefined && initialValue !== undefined) {
63
63
  var value = isFunction(initialValue) ? initialValue() : initialValue;
64
64
  state = globalState.set(path, value);
65
65
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/useGlobalState.js"],"names":["cloneDeep","isFunction","isUndefined","useEffect","useRef","useState","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","state","get","value","set","localState","setLocalState","callback","active","newState","watch","unWatch","ref","current","setter","newValue","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd"],"mappings":";AAAA;AAEA,SAASA,SAAT,EAAoBC,UAApB,EAAgCC,WAAhC,QAAmD,QAAnD;AACA,SAASC,SAAT,EAAoBC,MAApB,EAA4BC,QAA5B,QAA4C,OAA5C;AAEA,SAASC,cAAT;AACA,SAASC,WAAT;AAEA;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;;AACA,eAAe,SAASC,cAAT,CAAwBC,IAAxB,EAA8BC,YAA9B,EAA4C;AACzD,MAAMC,WAAW,GAAGL,cAAc,EAAlC;AACA,MAAIM,KAAK,GAAGD,WAAW,CAACE,GAAZ,CAAgBJ,IAAhB,CAAZ;;AACA,MAAIP,WAAW,CAACU,KAAD,CAAX,IAAsB,CAACV,WAAW,CAACQ,YAAD,CAAtC,EAAsD;AACpD,QAAMI,KAAK,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GACmBF,KADpC;;AAEA,YAAIa,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IAAyCtB,WAAW,EAAxD,EAA4D;AAC1D;AACAuB,UAAAA,OAAO,CAACC,cAAR,uEAEIR,GAAG,CAACC,OAAJ,CAAYf,IAAZ,IAAoB,EAFxB;AAKAqB,UAAAA,OAAO,CAACE,GAAR,CAAY,YAAZ,EAA0BhC,SAAS,CAAC0B,QAAD,CAAnC;AACAI,UAAAA,OAAO,CAACG,QAAR;AACA;AACD;;AAEDtB,QAAAA,WAAW,CAACI,GAAZ,CAAgBQ,GAAG,CAACC,OAAJ,CAAYf,IAA5B,EAAkCiB,QAAlC,EAfiB,CAiBjB;AACA;AACA;AACA;AACA;AACA;;AACAT,QAAAA,aAAa,CAAC;AAAA,iBAAMS,QAAN;AAAA,SAAD,CAAb;AACD;AA3BW,KAAd;AA6BD,GA9BD,MA8BO;AACLH,IAAAA,GAAG,CAACC,OAAJ,CAAYR,UAAZ,GAAyBA,UAAzB;AACAO,IAAAA,GAAG,CAACC,OAAJ,CAAYf,IAAZ,GAAmBA,IAAnB;AACD;;AAED,SAAO,CACLO,UADK,EAELO,GAAG,CAACC,OAAJ,CAAYC,MAFP,CAAP;AAID","sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction, isUndefined } from 'lodash';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport { isDebugMode } from './utils';\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 {string} [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 {any} [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 {Array} 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 */\nexport default function useGlobalState(path, initialValue) {\n const globalState = getGlobalState();\n let state = globalState.get(path);\n if (isUndefined(state) && !isUndefined(initialValue)) {\n const value = isFunction(initialValue) ? initialValue() : initialValue;\n state = globalState.set(path, value);\n }\n const [\n localState,\n setLocalState,\n ] = useState(() => state);\n\n useEffect(() => {\n // Note: the \"callback.active\" flag below is needed to workaround the issue\n // https://github.com/birdofpreyru/react-global-state/issues/33,\n // which, unfortunately, I am not able to reproduce in test environment,\n // but I definitely seen it in the wild.\n const callback = () => {\n if (callback.active) {\n const newState = globalState.get(path);\n if (newState !== localState) setLocalState(() => newState);\n }\n };\n callback.active = true;\n globalState.watch(callback);\n callback();\n return () => {\n delete callback.active;\n globalState.unWatch(callback);\n };\n }, [globalState, localState, path]);\n\n const ref = useRef();\n if (!ref.current) {\n ref.current = {\n localState,\n path,\n setter: (value) => {\n const newValue = isFunction(value)\n ? value(ref.current.localState) : value;\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n ref.current.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newValue));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n globalState.set(ref.current.path, newValue);\n\n // The update of local state here is important for managed inputs:\n // if we wait until the global state change notification is delivered\n // (which happens after the next React render), React won't conserve\n // the text cursor inside the currently focused input field (the cursor\n // will jump to the field end, like if the value was changed not by\n // keyboard input).\n setLocalState(() => newValue);\n },\n };\n } else {\n ref.current.localState = localState;\n ref.current.path = path;\n }\n\n return [\n localState,\n ref.current.setter,\n ];\n}\n"],"file":"useGlobalState.js"}
1
+ {"version":3,"sources":["../../src/useGlobalState.js"],"names":["cloneDeep","isFunction","useEffect","useRef","useState","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","state","get","undefined","value","set","localState","setLocalState","callback","active","newState","watch","unWatch","ref","current","setter","newValue","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd"],"mappings":";AAAA;AAEA,SAASA,SAAT,EAAoBC,UAApB,QAAsC,QAAtC;AACA,SAASC,SAAT,EAAoBC,MAApB,EAA4BC,QAA5B,QAA4C,OAA5C;AAEA,SAASC,cAAT;AACA,SAASC,WAAT;AAEA;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;;AACA,eAAe,SAASC,cAAT,CAAwBC,IAA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AAc;AACZR,MAAAA,UAAU,EAAVA,UADY;AAEZR,MAAAA,IAAI,EAAJA,IAFY;AAGZiB,MAAAA,MAAM,EAAE,gBAACX,KAAD,EAAW;AACjB,YAAMY,QAAQ,GAAGzB,UAAU,CAACa,KAAD,CAAV,GACbA,KAAK,CAACS,GAAG,CAACC,OAAJ,CAAYR,UAAb,CADQ,GACmBF,KADpC;;AAEA,YAAIa,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IAAyCvB,WAAW,EAAxD,EAA4D;AAC1D;AACAwB,UAAAA,OAAO,CAACC,cAAR,uEAEIR,GAAG,CAACC,OAAJ,CAAYhB,IAAZ,IAAoB,EAFxB;AAKAsB,UAAAA,OAAO,CAACE,GAAR,CAAY,YAAZ,EAA0BhC,SAAS,CAAC0B,QAAD,CAAnC;AACAI,UAAAA,OAAO,CAACG,QAAR;AACA;AACD;;AAEDvB,QAAAA,WAAW,CAACK,GAAZ,CAAgBQ,GAAG,CAACC,OAAJ,CAAYhB,IAA5B,EAAkCkB,QAAlC,EAfiB,CAiBjB;AACA;AACA;AACA;AACA;AACA;;AACAT,QAAAA,aAAa,CAAC;AAAA,iBAAMS,QAAN;AAAA,SAAD,CAAb;AACD;AA3BW,KAAd;AA6BD,GA9BD,MA8BO;AACLH,IAAAA,GAAG,CAACC,OAAJ,CAAYR,UAAZ,GAAyBA,UAAzB;AACAO,IAAAA,GAAG,CAACC,OAAJ,CAAYhB,IAAZ,GAAmBA,IAAnB;AACD;;AAED,SAAO,CACLQ,UADK,EAELO,GAAG,CAACC,OAAJ,CAAYC,MAFP,CAAP;AAID","sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport { isDebugMode } from './utils';\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 {string} [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 {any} [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 {Array} 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 */\nexport default function useGlobalState(path, initialValue) {\n const globalState = getGlobalState();\n let state = globalState.get(path);\n if (state === undefined && initialValue !== undefined) {\n const value = isFunction(initialValue) ? initialValue() : initialValue;\n state = globalState.set(path, value);\n }\n const [\n localState,\n setLocalState,\n ] = useState(() => state);\n\n useEffect(() => {\n // Note: the \"callback.active\" flag below is needed to workaround the issue\n // https://github.com/birdofpreyru/react-global-state/issues/33,\n // which, unfortunately, I am not able to reproduce in test environment,\n // but I definitely seen it in the wild.\n const callback = () => {\n if (callback.active) {\n const newState = globalState.get(path);\n if (newState !== localState) setLocalState(() => newState);\n }\n };\n callback.active = true;\n globalState.watch(callback);\n callback();\n return () => {\n delete callback.active;\n globalState.unWatch(callback);\n };\n }, [globalState, localState, path]);\n\n const ref = useRef();\n if (!ref.current) {\n ref.current = {\n localState,\n path,\n setter: (value) => {\n const newValue = isFunction(value)\n ? value(ref.current.localState) : value;\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n ref.current.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newValue));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n globalState.set(ref.current.path, newValue);\n\n // The update of local state here is important for managed inputs:\n // if we wait until the global state change notification is delivered\n // (which happens after the next React render), React won't conserve\n // the text cursor inside the currently focused input field (the cursor\n // will jump to the field end, like if the value was changed not by\n // keyboard input).\n setLocalState(() => newValue);\n },\n };\n } else {\n ref.current.localState = localState;\n ref.current.path = path;\n }\n\n return [\n localState,\n ref.current.setter,\n ];\n}\n"],"file":"useGlobalState.js"}
@@ -134,18 +134,23 @@ function useAsyncData(path, loader, options = {}) {
134
134
  } = options;
135
135
  if (maxage === undefined) maxage = DEFAULT_MAXAGE;
136
136
  if (refreshAge === undefined) refreshAge = maxage;
137
- if (garbageCollectAge === undefined) garbageCollectAge = maxage;
137
+ if (garbageCollectAge === undefined) garbageCollectAge = maxage; // Note: here we can't depend on useGlobalState() to init the initial value,
138
+ // because that way we'll have issues with SSR (see details below).
139
+
138
140
  const globalState = (0, _GlobalStateProvider.getGlobalState)();
139
- const [localState] = (0, _useGlobalState.default)(path, {
140
- data: null,
141
- numRefs: 0,
142
- operationId: '',
143
- timestamp: 0
144
- });
141
+ let state = globalState.get(path);
145
142
 
146
- if (globalState.ssrContext && !options.noSSR) {
147
- const state = globalState.get(path);
143
+ if (state === undefined) {
144
+ state = {
145
+ data: null,
146
+ numRefs: 0,
147
+ operationId: '',
148
+ timestamp: 0
149
+ };
150
+ globalState.set(path, state);
151
+ }
148
152
 
153
+ if (globalState.ssrContext && !options.noSSR) {
149
154
  if (!state.timestamp && !state.operationId) {
150
155
  globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
151
156
  }
@@ -165,21 +170,21 @@ function useAsyncData(path, loader, options = {}) {
165
170
  const numRefs = globalState.get(numRefsPath);
166
171
  globalState.set(numRefsPath, numRefs + 1);
167
172
  return () => {
168
- const state = globalState.get(path);
173
+ const state2 = globalState.get(path);
169
174
 
170
- if (state.numRefs === 1 && garbageCollectAge < Date.now() - state.timestamp) {
175
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
171
176
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
172
177
  /* eslint-disable no-console */
173
178
  console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
174
179
  /* eslint-enable no-console */
175
180
  }
176
181
 
177
- globalState.set(path, { ...state,
182
+ globalState.set(path, { ...state2,
178
183
  data: null,
179
184
  numRefs: 0,
180
185
  timestamp: 0
181
186
  });
182
- } else globalState.set(numRefsPath, state.numRefs - 1);
187
+ } else globalState.set(numRefsPath, state2.numRefs - 1);
183
188
  };
184
189
  }, [garbageCollectAge, globalState, path]); // Note: a bunch of Rules of Hooks ignored belows because in our very
185
190
  // special case the otherwise wrong behavior is actually what we need.
@@ -188,10 +193,10 @@ function useAsyncData(path, loader, options = {}) {
188
193
  let loadTriggered = false;
189
194
  (0, _react.useEffect)(() => {
190
195
  // eslint-disable-line react-hooks/rules-of-hooks
191
- const state = globalState.get(path);
196
+ const state2 = globalState.get(path);
192
197
 
193
- if (refreshAge < Date.now() - state.timestamp && (!state.operationId || state.operationId.charAt() === 'S')) {
194
- load(path, loader, globalState, state.data);
198
+ if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt() === 'S')) {
199
+ load(path, loader, globalState, state2.data);
195
200
  loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
196
201
  }
197
202
  });
@@ -200,8 +205,14 @@ function useAsyncData(path, loader, options = {}) {
200
205
  // eslint-disable-line react-hooks/rules-of-hooks
201
206
  if (!loadTriggered && deps.length) load(path, loader, globalState);
202
207
  }, deps); // eslint-disable-line react-hooks/exhaustive-deps
203
- }
208
+ } // Note: this subscription to updates of the global state segment must be
209
+ // here, after the possible initialization of the loading operation, to take
210
+ // into effect the resulting loading state. This mostly ensures the correct
211
+ // SSR in the edge case when the loading starts, but times out, and incomplete
212
+ // render has to be served.
213
+
204
214
 
215
+ const [localState] = (0, _useGlobalState.default)(path);
205
216
  return {
206
217
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
207
218
  loading: Boolean(localState.operationId),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/useAsyncData.js"],"names":["DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationId","operationIdPath","set","data","get","state","groupCollapsed","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","localState","numRefs","ssrContext","noSSR","pending","push","numRefsPath","loadTriggered","charAt","deps","length","loading","Boolean"],"mappings":";;;;;;;;;AAIA;;AACA;;AACA;;AAEA;;AACA;;AACA;;AAVA;AACA;AACA;AAUA,MAAMA,cAAc,GAAG,IAAI,EAAJ,GAAS,IAAhC,C,CAAsC;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,eAAeC,IAAf,CAAoBC,IAApB,EAA0BC,MAA1B,EAAkCC,WAAlC,EAA+CC,OAA/C,EAAwDC,UAAU,GAAG,GAArE,EAA0E;AACxE,MAAIC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,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,CAAJ,EAC+D;AAC7DpC,QAAAA,IAAI,CAACC,IAAD,EAAOC,MAAP,EAAeC,WAAf,EAA4Ba,KAAK,CAACF,IAAlC,CAAJ;AACAqB,QAAAA,aAAa,GAAG,IAAhB,CAF6D,CAEvC;AACvB;AACF,KAPD;AASA,UAAME,IAAI,GAAGd,OAAO,CAACc,IAAR,IAAgB,EAA7B;AACA,0BAAU,MAAM;AAAE;AAChB,UAAI,CAACF,aAAD,IAAkBE,IAAI,CAACC,MAA3B,EAAmCtC,IAAI,CAACC,IAAD,EAAOC,MAAP,EAAeC,WAAf,CAAJ;AACpC,KAFD,EAEGkC,IAFH,EAtDK,CAwDK;AACX;;AAED,SAAO;AACLvB,IAAAA,IAAI,EAAEW,MAAM,GAAGN,IAAI,CAACC,GAAL,KAAaQ,UAAU,CAACV,SAAjC,GAA6C,IAA7C,GAAoDU,UAAU,CAACd,IADhE;AAELyB,IAAAA,OAAO,EAAEC,OAAO,CAACZ,UAAU,CAACjB,WAAZ,CAFX;AAGLO,IAAAA,SAAS,EAAEU,UAAU,CAACV;AAHjB,GAAP;AAKD","sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [oldData] Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param {object} [options] Additional options.\n * @param {any[]} [options.deps=[]] An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param {number} [options.refreshAge=maxage] The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) garbageCollectAge = maxage;\n\n const globalState = getGlobalState();\n const [localState] = useGlobalState(path, {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n const state = globalState.get(path);\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state = globalState.get(path);\n if (\n state.numRefs === 1\n && garbageCollectAge < Date.now() - state.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(numRefsPath, state.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state = globalState.get(path);\n if (refreshAge < Date.now() - state.timestamp\n && (!state.operationId || state.operationId.charAt() === 'S')) {\n load(path, loader, globalState, state.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n"],"file":"useAsyncData.js"}
1
+ {"version":3,"sources":["../../src/useAsyncData.js"],"names":["DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationId","operationIdPath","set","data","get","state","groupCollapsed","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","numRefs","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered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U,CAACrB;AAHjB,GAAP;AAKD","sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [oldData] Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param {object} [options] Additional options.\n * @param {any[]} [options.deps=[]] An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param {number} [options.refreshAge=maxage] The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) garbageCollectAge = maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n let state = globalState.get(path);\n if (state === undefined) {\n state = {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n globalState.set(path, state);\n }\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state2 = globalState.get(path);\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2 = globalState.get(path);\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt() === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n // Note: this subscription to updates of the global state segment must be\n // here, after the possible initialization of the loading operation, to take\n // into effect the resulting loading state. This mostly ensures the correct\n // SSR in the edge case when the loading starts, but times out, and incomplete\n // render has to be served.\n const [localState] = useGlobalState(path);\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n"],"file":"useAsyncData.js"}
@@ -69,7 +69,7 @@ function useGlobalState(path, initialValue) {
69
69
  const globalState = (0, _GlobalStateProvider.getGlobalState)();
70
70
  let state = globalState.get(path);
71
71
 
72
- if ((0, _lodash.isUndefined)(state) && !(0, _lodash.isUndefined)(initialValue)) {
72
+ if (state === undefined && initialValue !== undefined) {
73
73
  const value = (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue;
74
74
  state = globalState.set(path, value);
75
75
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/useGlobalState.js"],"names":["useGlobalState","path","initialValue","globalState","state","get","value","set","localState","setLocalState","callback","active","newState","watch","unWatch","ref","current","setter","newValue","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd"],"mappings":";;;;;;;AAEA;;AACA;;AAEA;;AACA;;AANA;;AAQA;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;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AEZP,MAAAA,IAFY;AAGZgB,MAAAA,MAAM,EAAGX,KAAD,IAAW;AACjB,cAAMY,QAAQ,GAAG,wBAAWZ,KAAX,IACbA,KAAK,CAACS,GAAG,CAACC,OAAJ,CAAYR,UAAb,CADQ,GACmBF,KADpC;;AAEA,YAAIa,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IAAyC,yBAA7C,EAA4D;AAC1D;AACAC,UAAAA,OAAO,CAACC,cAAR,CACG,+DACCR,GAAG,CAACC,OAAJ,CAAYf,IAAZ,IAAoB,EACrB,EAHH;AAKAqB,UAAAA,OAAO,CAACE,GAAR,CAAY,YAAZ,EAA0B,uBAAUN,QAAV,CAA1B;AACAI,UAAAA,OAAO,CAACG,QAAR;AACA;AACD;;AAEDtB,QAAAA,WAAW,CAACI,GAAZ,CAAgBQ,GAAG,CAACC,OAAJ,CAAYf,IAA5B,EAAkCiB,QAAlC,EAfiB,CAiBjB;AACA;AACA;AACA;AACA;AACA;;AACAT,QAAAA,aAAa,CAAC,MAAMS,QAAP,CAAb;AACD;AA3BW,KAAd;AA6BD,GA9BD,MA8BO;AACLH,IAAAA,GAAG,CAACC,OAAJ,CAAYR,UAAZ,GAAyBA,UAAzB;AACAO,IAAAA,GAAG,CAACC,OAAJ,CAAYf,IAAZ,GAAmBA,IAAnB;AACD;;AAED,SAAO,CACLO,UADK,EAELO,GAAG,CAACC,OAAJ,CAAYC,MAFP,CAAP;AAID","sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction, isUndefined } from 'lodash';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport { isDebugMode } from './utils';\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 {string} [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 {any} [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 {Array} 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 */\nexport default function useGlobalState(path, initialValue) {\n const globalState = getGlobalState();\n let state = globalState.get(path);\n if (isUndefined(state) && !isUndefined(initialValue)) {\n const value = isFunction(initialValue) ? initialValue() : initialValue;\n state = globalState.set(path, value);\n }\n const [\n localState,\n setLocalState,\n ] = useState(() => state);\n\n useEffect(() => {\n // Note: the \"callback.active\" flag below is needed to workaround the issue\n // https://github.com/birdofpreyru/react-global-state/issues/33,\n // which, unfortunately, I am not able to reproduce in test environment,\n // but I definitely seen it in the wild.\n const callback = () => {\n if (callback.active) {\n const newState = globalState.get(path);\n if (newState !== localState) setLocalState(() => newState);\n }\n };\n callback.active = true;\n globalState.watch(callback);\n callback();\n return () => {\n delete callback.active;\n globalState.unWatch(callback);\n };\n }, [globalState, localState, path]);\n\n const ref = useRef();\n if (!ref.current) {\n ref.current = {\n localState,\n path,\n setter: (value) => {\n const newValue = isFunction(value)\n ? value(ref.current.localState) : value;\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n ref.current.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newValue));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n globalState.set(ref.current.path, newValue);\n\n // The update of local state here is important for managed inputs:\n // if we wait until the global state change notification is delivered\n // (which happens after the next React render), React won't conserve\n // the text cursor inside the currently focused input field (the cursor\n // will jump to the field end, like if the value was changed not by\n // keyboard input).\n setLocalState(() => newValue);\n },\n };\n } else {\n ref.current.localState = localState;\n ref.current.path = path;\n }\n\n return [\n localState,\n ref.current.setter,\n ];\n}\n"],"file":"useGlobalState.js"}
1
+ {"version":3,"sources":["../../src/useGlobalState.js"],"names":["useGlobalState","path","initialValue","globalState","state","get","undefined","value","set","localState","setLocalState","callback","active","newState","watch","unWatch","ref","current","setter","newValue","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd"],"mappings":";;;;;;;AAEA;;AACA;;AAEA;;AACA;;AANA;;AAQA;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;AACe,SAASA,cAAT,CAAwBC,IAAxB,EAA8BC,YAA9B,EAA4C;AACzD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ACC,OAAJ,CAAYR,UAAb,CADQ,GACmBF,KADpC;;AAEA,YAAIa,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IAAyC,yBAA7C,EAA4D;AAC1D;AACAC,UAAAA,OAAO,CAACC,cAAR,CACG,+DACCR,GAAG,CAACC,OAAJ,CAAYhB,IAAZ,IAAoB,EACrB,EAHH;AAKAsB,UAAAA,OAAO,CAACE,GAAR,CAAY,YAAZ,EAA0B,uBAAUN,QAAV,CAA1B;AACAI,UAAAA,OAAO,CAACG,QAAR;AACA;AACD;;AAEDvB,QAAAA,WAAW,CAACK,GAAZ,CAAgBQ,GAAG,CAACC,OAAJ,CAAYhB,IAA5B,EAAkCkB,QAAlC,EAfiB,CAiBjB;AACA;AACA;AACA;AACA;AACA;;AACAT,QAAAA,aAAa,CAAC,MAAMS,QAAP,CAAb;AACD;AA3BW,KAAd;AA6BD,GA9BD,MA8BO;AACLH,IAAAA,GAAG,CAACC,OAAJ,CAAYR,UAAZ,GAAyBA,UAAzB;AACAO,IAAAA,GAAG,CAACC,OAAJ,CAAYhB,IAAZ,GAAmBA,IAAnB;AACD;;AAED,SAAO,CACLQ,UADK,EAELO,GAAG,CAACC,OAAJ,CAAYC,MAFP,CAAP;AAID","sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport { isDebugMode } from './utils';\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 {string} [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 {any} [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 {Array} 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 */\nexport default function useGlobalState(path, initialValue) {\n const globalState = getGlobalState();\n let state = globalState.get(path);\n if (state === undefined && initialValue !== undefined) {\n const value = isFunction(initialValue) ? initialValue() : initialValue;\n state = globalState.set(path, value);\n }\n const [\n localState,\n setLocalState,\n ] = useState(() => state);\n\n useEffect(() => {\n // Note: the \"callback.active\" flag below is needed to workaround the issue\n // https://github.com/birdofpreyru/react-global-state/issues/33,\n // which, unfortunately, I am not able to reproduce in test environment,\n // but I definitely seen it in the wild.\n const callback = () => {\n if (callback.active) {\n const newState = globalState.get(path);\n if (newState !== localState) setLocalState(() => newState);\n }\n };\n callback.active = true;\n globalState.watch(callback);\n callback();\n return () => {\n delete callback.active;\n globalState.unWatch(callback);\n };\n }, [globalState, localState, path]);\n\n const ref = useRef();\n if (!ref.current) {\n ref.current = {\n localState,\n path,\n setter: (value) => {\n const newValue = isFunction(value)\n ? value(ref.current.localState) : value;\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n ref.current.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newValue));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n globalState.set(ref.current.path, newValue);\n\n // The update of local state here is important for managed inputs:\n // if we wait until the global state change notification is delivered\n // (which happens after the next React render), React won't conserve\n // the text cursor inside the currently focused input field (the cursor\n // will jump to the field end, like if the value was changed not by\n // keyboard input).\n setLocalState(() => newValue);\n },\n };\n } else {\n ref.current.localState = localState;\n ref.current.path = path;\n }\n\n return [\n localState,\n ref.current.setter,\n ];\n}\n"],"file":"useGlobalState.js"}
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.7.1",
3
+ "version": "0.8.2",
4
4
  "description": "Hook-based global state for React",
5
5
  "main": "./build/node/index.js",
6
6
  "exports": {
7
+ "default": "./build/node/index.js",
7
8
  "module": "./build/module/index.js",
8
9
  "node": "./build/node/index.js",
9
10
  "types": "./index.d.ts"
@@ -34,38 +35,37 @@
34
35
  },
35
36
  "homepage": "https://dr.pogodin.studio/docs/react-global-state/index.html",
36
37
  "dependencies": {
37
- "@babel/runtime": "^7.17.2",
38
+ "@babel/runtime": "^7.17.9",
38
39
  "lodash": "^4.17.21",
39
40
  "uuid": "^8.3.2"
40
41
  },
41
42
  "devDependencies": {
42
43
  "@babel/cli": "^7.17.6",
43
- "@babel/core": "^7.17.5",
44
+ "@babel/core": "^7.17.9",
44
45
  "@babel/eslint-parser": "^7.17.0",
45
- "@babel/eslint-plugin": "^7.16.5",
46
+ "@babel/eslint-plugin": "^7.17.7",
46
47
  "@babel/node": "^7.16.8",
47
48
  "@babel/plugin-transform-runtime": "^7.17.0",
48
49
  "@babel/preset-env": "^7.16.11",
49
50
  "@babel/preset-react": "^7.16.7",
50
- "babel-jest": "^27.5.1",
51
+ "babel-jest": "^28.0.0",
51
52
  "babel-plugin-module-resolver": "^4.1.0",
52
- "eslint": "^8.10.0",
53
+ "eslint": "^8.14.0",
53
54
  "eslint-config-airbnb": "^19.0.4",
54
55
  "eslint-import-resolver-babel-module": "^5.3.1",
55
- "eslint-plugin-import": "^2.25.4",
56
- "eslint-plugin-jest": "^26.1.1",
56
+ "eslint-plugin-import": "^2.26.0",
57
+ "eslint-plugin-jest": "^26.1.5",
57
58
  "eslint-plugin-jsx-a11y": "^6.5.1",
58
- "eslint-plugin-react": "^7.29.3",
59
- "eslint-plugin-react-hooks": "^4.3.0",
60
- "jest": "^27.5.1",
59
+ "eslint-plugin-react": "^7.29.4",
60
+ "eslint-plugin-react-hooks": "^4.4.0",
61
+ "jest": "^28.0.0",
62
+ "jest-environment-jsdom": "^28.0.0",
61
63
  "mockdate": "^3.0.5",
62
64
  "pretty": "^2.0.0",
63
- "react": "^17.0.2",
64
- "react-dom": "^17.0.2",
65
65
  "rimraf": "^3.0.2"
66
66
  },
67
67
  "peerDependencies": {
68
- "react": "^17.0.2",
69
- "react-dom": "^17.0.2"
68
+ "react": "^18.0.0",
69
+ "react-dom": "^18.0.0"
70
70
  }
71
71
  }