@dr.pogodin/react-global-state 0.8.3 → 0.9.0

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,7 +1,6 @@
1
- import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
2
1
  // Hook for updates of global state.
3
2
  import { cloneDeep, isFunction } from 'lodash';
4
- import { useEffect, useRef, useState } from 'react';
3
+ import { useEffect, useRef, useSyncExternalStore } from 'react';
5
4
  import { getGlobalState } from "./GlobalStateProvider";
6
5
  import { isDebugMode } from "./utils";
7
6
  /**
@@ -56,77 +55,64 @@ import { isDebugMode } from "./utils";
56
55
  */
57
56
 
58
57
  export default function useGlobalState(path, initialValue) {
59
- var globalState = getGlobalState();
60
- var state = globalState.get(path);
61
-
62
- if (state === undefined && initialValue !== undefined) {
63
- var value = isFunction(initialValue) ? initialValue() : initialValue;
64
- state = globalState.set(path, value);
65
- }
66
-
67
- var _useState = useState(function () {
68
- return state;
69
- }),
70
- _useState2 = _slicedToArray(_useState, 2),
71
- localState = _useState2[0],
72
- setLocalState = _useState2[1];
73
-
74
- useEffect(function () {
75
- // Note: the "callback.active" flag below is needed to workaround the issue
76
- // https://github.com/birdofpreyru/react-global-state/issues/33,
77
- // which, unfortunately, I am not able to reproduce in test environment,
78
- // but I definitely seen it in the wild.
79
- var callback = function callback() {
80
- if (callback.active) {
81
- var newState = globalState.get(path);
82
- if (newState !== localState) setLocalState(function () {
83
- return newState;
84
- });
85
- }
86
- };
87
-
88
- callback.active = true;
89
- globalState.watch(callback);
90
- callback();
91
- return function () {
92
- delete callback.active;
93
- globalState.unWatch(callback);
94
- };
95
- }, [globalState, localState, path]);
96
58
  var ref = useRef();
97
59
 
98
60
  if (!ref.current) {
99
61
  ref.current = {
100
- localState: localState,
101
- path: path,
62
+ callbacks: [],
102
63
  setter: function setter(value) {
103
- var newValue = isFunction(value) ? value(ref.current.localState) : value;
64
+ var rc = ref.current;
65
+ var newState = isFunction(value) ? value(rc.state) : value;
104
66
 
105
67
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
106
68
  /* eslint-disable no-console */
107
- console.groupCollapsed("ReactGlobalState - useGlobalState setter triggered for path ".concat(ref.current.path || ''));
108
- console.log('New value:', cloneDeep(newValue));
69
+ console.groupCollapsed("ReactGlobalState - useGlobalState setter triggered for path ".concat(rc.path || ''));
70
+ console.log('New value:', cloneDeep(newState));
109
71
  console.groupEnd();
110
72
  /* eslint-enable no-console */
111
73
  }
112
74
 
113
- globalState.set(ref.current.path, newValue); // The update of local state here is important for managed inputs:
114
- // if we wait until the global state change notification is delivered
115
- // (which happens after the next React render), React won't conserve
116
- // the text cursor inside the currently focused input field (the cursor
117
- // will jump to the field end, like if the value was changed not by
118
- // keyboard input).
75
+ rc.globalState.set(rc.path, newState);
76
+ },
77
+ watcher: function watcher() {
78
+ var rc = ref.current;
79
+ var state = rc.globalState.get(rc.path);
119
80
 
120
- setLocalState(function () {
121
- return newValue;
122
- });
81
+ if (state !== rc.state) {
82
+ for (var i = 0; i < rc.callbacks.length; ++i) {
83
+ rc.callbacks[i]();
84
+ }
85
+ }
123
86
  }
124
87
  };
125
- } else {
126
- ref.current.localState = localState;
127
- ref.current.path = path;
128
88
  }
129
89
 
130
- return [localState, ref.current.setter];
90
+ var rc = ref.current;
91
+ var globalState = getGlobalState();
92
+ rc.globalState = globalState;
93
+ rc.path = path;
94
+ rc.state = useSyncExternalStore(function (cb) {
95
+ rc.callbacks.push(cb);
96
+ }, function () {
97
+ return rc.globalState.get(rc.path, {
98
+ initialValue: initialValue
99
+ });
100
+ }, function () {
101
+ return rc.globalState.get(rc.path, {
102
+ initialValue: initialValue,
103
+ initialState: true
104
+ });
105
+ });
106
+ useEffect(function () {
107
+ globalState.watch(rc.watcher);
108
+ rc.watcher();
109
+ return function () {
110
+ return globalState.unWatch(rc.watcher);
111
+ };
112
+ }, [globalState, rc]);
113
+ useEffect(function () {
114
+ rc.watcher();
115
+ }, [path, rc]);
116
+ return [rc.state, rc.setter];
131
117
  }
132
118
  //# sourceMappingURL=useGlobalState.js.map
@@ -1 +1 @@
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,IAAxB,EAA8BC,YAA9B,EAA4C;AACzD,MAAMC,WAAW,GAAGL,cAAc,EAAlC;AACA,MAAIM,KAAK,GAAGD,WAAW,CAACE,GAAZ,CAAgBJ,IAAhB,CAAZ;;AACA,MAAIG,KAAK,KAAKE,SAAV,IAAuBJ,YAAY,KAAKI,SAA5C,EAAuD;AACrD,QAAMC,KAAK,GAAGb,UAAU,CAACQ,YAAD,CAAV,GAA2BA,YAAY,EAAvC,GAA4CA,YAA1D;AACAE,IAAAA,KAAK,GAAGD,WAAW,CAACK,GAAZ,CAAgBP,IAAhB,EAAsBM,KAAtB,CAAR;AACD;;AACD,kBAGIV,QAAQ,CAAC;AAAA,WAAMO,KAAN;AAAA,GAAD,CAHZ;AAAA;AAAA,MACEK,UADF;AAAA,MAEEC,aAFF;;AAKAf,EAAAA,SAAS,CAAC,YAAM;AACd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AAO,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"}
1
+ {"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","getGlobalState","isDebugMode","useGlobalState","path","initialValue","ref","current","callbacks","setter","value","rc","newState","state","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","globalState","set","watcher","get","i","length","cb","push","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.js"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } 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 ref = useRef();\n if (!ref.current) {\n ref.current = {\n callbacks: [],\n setter: (value) => {\n const rc = ref.current;\n const newState = isFunction(value) ? value(rc.state) : 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 rc.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set(rc.path, newState);\n },\n watcher: () => {\n const rc = ref.current;\n const state = rc.globalState.get(rc.path);\n if (state !== rc.state) {\n for (let i = 0; i < rc.callbacks.length; ++i) {\n rc.callbacks[i]();\n }\n }\n },\n };\n }\n\n const rc = ref.current;\n const globalState = getGlobalState();\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n (cb) => { rc.callbacks.push(cb); },\n () => rc.globalState.get(rc.path, { initialValue }),\n () => rc.globalState.get(rc.path, { initialValue, initialState: true }),\n );\n\n useEffect(() => {\n globalState.watch(rc.watcher);\n rc.watcher();\n return () => globalState.unWatch(rc.watcher);\n }, [globalState, rc]);\n\n useEffect(() => {\n rc.watcher();\n }, [path, rc]);\n\n return [rc.state, rc.setter];\n}\n"],"mappings":"AAAA;AAEA,SAASA,SAAT,EAAoBC,UAApB,QAAsC,QAAtC;AACA,SAASC,SAAT,EAAoBC,MAApB,EAA4BC,oBAA5B,QAAwD,OAAxD;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;EACzD,IAAMC,GAAG,GAAGP,MAAM,EAAlB;;EACA,IAAI,CAACO,GAAG,CAACC,OAAT,EAAkB;IAChBD,GAAG,CAACC,OAAJ,GAAc;MACZC,SAAS,EAAE,EADC;MAEZC,MAAM,EAAE,gBAACC,KAAD,EAAW;QACjB,IAAMC,EAAE,GAAGL,GAAG,CAACC,OAAf;QACA,IAAMK,QAAQ,GAAGf,UAAU,CAACa,KAAD,CAAV,GAAoBA,KAAK,CAACC,EAAE,CAACE,KAAJ,CAAzB,GAAsCH,KAAvD;;QACA,IAAII,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IAAyCd,WAAW,EAAxD,EAA4D;UAC1D;UACAe,OAAO,CAACC,cAAR,uEAEIP,EAAE,CAACP,IAAH,IAAW,EAFf;UAKAa,OAAO,CAACE,GAAR,CAAY,YAAZ,EAA0BvB,SAAS,CAACgB,QAAD,CAAnC;UACAK,OAAO,CAACG,QAAR;UACA;QACD;;QACDT,EAAE,CAACU,WAAH,CAAeC,GAAf,CAAmBX,EAAE,CAACP,IA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AAvB,CAAN;IAAA,CAAP;EACD,CAJQ,EAIN,CAACF,WAAD,EAAcV,EAAd,CAJM,CAAT;EAMAb,SAAS,CAAC,YAAM;IACda,EAAE,CAACY,OAAH;EACD,CAFQ,EAEN,CAACnB,IAAD,EAAOO,EAAP,CAFM,CAAT;EAIA,OAAO,CAACA,EAAE,CAACE,KAAJ,EAAWF,EAAE,CAACF,MAAd,CAAP;AACD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils.js"],"names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"mappings":"AAAA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,WAAT,GAAuB;AAC5B,MAAI;AACF,WAAOC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IACF,CAAC,CAACF,OAAO,CAACC,GAAR,CAAYE,wBADnB;AAED,GAHD,CAGE,OAAOC,KAAP,EAAc;AACd,WAAO,KAAP;AACD;AACF;AAED,eAAe,IAAf","sourcesContent":["// Auxiliary stuff.\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns {boolean}\n * @ignore\n */\nexport function isDebugMode() {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n\nexport default null;\n"],"file":"utils.js"}
1
+ {"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"sources":["../../src/utils.js"],"sourcesContent":["// Auxiliary stuff.\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns {boolean}\n * @ignore\n */\nexport function isDebugMode() {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n\nexport default null;\n"],"mappings":"AAAA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,WAAT,GAAuB;EAC5B,IAAI;IACF,OAAOC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IACF,CAAC,CAACF,OAAO,CAACC,GAAR,CAAYE,wBADnB;EAED,CAHD,CAGE,OAAOC,KAAP,EAAc;IACd,OAAO,KAAP;EACD;AACF;AAED,eAAe,IAAf"}
@@ -10,34 +10,31 @@ var _lodash = require("lodash");
10
10
  var _utils = require("./utils");
11
11
 
12
12
  const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
13
- /**
14
- * Transform state path into the full path inside GlobalState object.
15
- * @param {string} statePath
16
- * @return {string}
17
- * @ignore
18
- */
19
-
20
- function fullPath(statePath) {
21
- return (0, _lodash.isNil)(statePath) ? 'state' : `state.${statePath}`;
22
- }
23
13
 
24
14
  class GlobalState {
15
+ #initialState;
16
+ #nextNotifierId = null;
17
+ #ssrContext;
18
+ #currentState;
19
+ #watchers = [];
25
20
  /**
26
21
  * Creates a new global state object.
27
22
  * @param {any} [initialState] Intial global state content.
28
23
  * @param {SsrContext} [ssrContext] Server-side rendering context.
29
24
  */
25
+
30
26
  constructor(initialState, ssrContext) {
31
- /* eslint-disable no-param-reassign */
32
- this.state = (0, _lodash.cloneDeep)(initialState);
33
- this.nextNotifierId = null;
34
- this.watchers = [];
27
+ this.#currentState = initialState;
28
+ this.#initialState = initialState;
35
29
 
36
30
  if (ssrContext) {
31
+ /* eslint-disable no-param-reassign */
37
32
  ssrContext.dirty = false;
38
33
  ssrContext.pending = [];
39
- ssrContext.state = this.state;
40
- this.ssrContext = ssrContext;
34
+ ssrContext.state = this.#currentState;
35
+ /* eslint-enable no-param-reassign */
36
+
37
+ this.#ssrContext = ssrContext;
41
38
  }
42
39
 
43
40
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
@@ -49,20 +46,37 @@ class GlobalState {
49
46
  console.groupEnd();
50
47
  /* eslint-enable no-console */
51
48
  }
52
- /* eslint-enable no-param-reassign */
53
-
54
49
  }
55
50
  /**
56
- * Gets the value at given `path` of global state. If `path` is null or
57
- * undefined, the entire state object is returned.
58
- * @param {string} [path] Dot-delimitered state path. If not given, entire
59
- * global state content is returned.
60
- * @return {any}
51
+ * Gets current or initial value at the specified "path" of the global state.
52
+ * Allows to get the entire global state, and automatically set default value
53
+ * at the "path".
54
+ * @param {string} [path] Dot-delimitered state path. Pass it "null",
55
+ * or "undefined" to refer the entire global state.
56
+ * @param {object} [options={}] Additional options.
57
+ * @param {boolean} [options.initialState] If "true" the value will be read
58
+ * from the initial state instead of the current one.
59
+ * @param {any} [options.initialValue] If the value read from the "path" is
60
+ * "undefined", this "initialValue" will be returned instead. In such case
61
+ * "initialValue" will also be written to the "path" of the current global
62
+ * state (no matter "initialState" flag), if "undefined" is stored there.
63
+ * @return {any} Retrieved value.
61
64
  */
62
65
 
63
66
 
64
- get(path) {
65
- return (0, _lodash.get)(this, fullPath(path));
67
+ get(path, {
68
+ initialState,
69
+ initialValue
70
+ } = {}) {
71
+ const state = initialState ? this.#initialState : this.#currentState;
72
+ let value = (0, _lodash.isNil)(path) ? state : (0, _lodash.get)(state, path);
73
+
74
+ if (value === undefined && initialValue !== undefined) {
75
+ value = (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue;
76
+ if (!initialState || this.get(path) === undefined) this.set(path, value);
77
+ }
78
+
79
+ return value;
66
80
  }
67
81
  /**
68
82
  * Writes the `value` to given global state `path`.
@@ -74,9 +88,7 @@ class GlobalState {
74
88
 
75
89
 
76
90
  set(path, value) {
77
- const p = fullPath(path);
78
-
79
- if (value !== (0, _lodash.get)(this, p)) {
91
+ if (value !== this.get(path)) {
80
92
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
81
93
  /* eslint-disable no-console */
82
94
  console.groupCollapsed(`ReactGlobalState update. Path: "${path || ''}"`);
@@ -84,37 +96,48 @@ class GlobalState {
84
96
  /* eslint-enable no-console */
85
97
  }
86
98
 
87
- let pos = this;
88
- const pathSegments = (0, _lodash.toPath)(p);
89
-
90
- for (let i = 0; i < pathSegments.length - 1; i += 1) {
91
- const seg = pathSegments[i];
92
- const next = pos[seg];
93
- if ((0, _lodash.isArray)(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = { ...next
94
- };else break;
95
- pos = pos[seg];
96
- } // TODO: With such naive use of _.set, the state is mutated in place,
97
- // which may cause tons of unexpected side effects for dependants.
98
- // It will be better to partially clone the state, so that any existing
99
- // references are not mutated, while the full deep clonning is also
100
- // avoided.
101
-
102
-
103
- (0, _lodash.set)(this, p, value);
104
-
105
- if (this.ssrContext) {
106
- this.ssrContext.dirty = true;
107
- this.ssrContext.state = this.state;
108
- } else if (!this.nextNotifierId) {
109
- this.nextNotifierId = setTimeout(() => {
110
- this.nextNotifierId = null;
111
- [...this.watchers].forEach(w => w());
99
+ if ((0, _lodash.isNil)(path)) this.#currentState = value;else {
100
+ const root = {
101
+ state: this.#currentState
102
+ };
103
+ let segIdx = 0;
104
+ let pos = root;
105
+ const pathSegments = (0, _lodash.toPath)(`state.${path}`);
106
+
107
+ for (; segIdx < pathSegments.length - 1; segIdx += 1) {
108
+ const seg = pathSegments[segIdx];
109
+ const next = pos[seg];
110
+ if (Array.isArray(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = { ...next
111
+ };else {
112
+ // We arrived to a state sub-segment, where the remaining part of
113
+ // the update path does not exist yet. We rely on lodash's set()
114
+ // function to create the remaining path, and set the value.
115
+ (0, _lodash.set)(pos, pathSegments.slice(segIdx), value);
116
+ break;
117
+ }
118
+ pos = pos[seg];
119
+ }
120
+
121
+ if (segIdx === pathSegments.length - 1) {
122
+ pos[pathSegments[segIdx]] = value;
123
+ }
124
+
125
+ this.#currentState = root.state;
126
+ }
127
+
128
+ if (this.#ssrContext) {
129
+ this.#ssrContext.dirty = true;
130
+ this.#ssrContext.state = this.#currentState;
131
+ } else if (!this.#nextNotifierId) {
132
+ this.#nextNotifierId = setTimeout(() => {
133
+ this.#nextNotifierId = null;
134
+ [...this.#watchers].forEach(w => w());
112
135
  });
113
136
  }
114
137
 
115
138
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
116
139
  /* eslint-disable no-console */
117
- console.log('New state:', (0, _lodash.cloneDeep)(this.state));
140
+ console.log('New state:', (0, _lodash.cloneDeep)(this.#currentState));
118
141
  console.groupEnd();
119
142
  /* eslint-enable no-console */
120
143
  }
@@ -132,10 +155,8 @@ class GlobalState {
132
155
 
133
156
 
134
157
  unWatch(callback) {
135
- if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
136
- const {
137
- watchers
138
- } = this;
158
+ if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);
159
+ const watchers = this.#watchers;
139
160
  const pos = watchers.indexOf(callback);
140
161
 
141
162
  if (pos >= 0) {
@@ -143,6 +164,10 @@ class GlobalState {
143
164
  watchers.pop();
144
165
  }
145
166
  }
167
+
168
+ get ssrContext() {
169
+ return this.#ssrContext;
170
+ }
146
171
  /**
147
172
  * Subscribes `callback` to watch state updates; no operation if
148
173
  * `callback` is already subscribed to this state instance.
@@ -156,10 +181,8 @@ class GlobalState {
156
181
 
157
182
 
158
183
  watch(callback) {
159
- if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
160
- const {
161
- watchers
162
- } = this;
184
+ if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);
185
+ const watchers = this.#watchers;
163
186
 
164
187
  if (watchers.indexOf(callback) < 0) {
165
188
  watchers.push(callback);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/GlobalState.js"],"names":["ERR_NO_SSR_WATCH","fullPath","statePath","GlobalState","constructor","initialState","ssrContext","state","nextNotifierId","watchers","dirty","pending","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","get","path","set","value","p","pos","pathSegments","i","length","seg","next","setTimeout","forEach","w","unWatch","callback","Error","indexOf","pop","watch","push"],"mappings":";;;;;;;AAAA;;AAUA;;AAEA,MAAMA,gBAAgB,GAAG,gDAAzB;AAEA;AACA;AACA;AACA;AACA;AACA;;AACA,SAASC,QAAT,CAAkBC,SAAlB,EAA6B;AAC3B,SAAO,mBAAMA,SAAN,IAAmB,OAAnB,GAA8B,SAAQA,SAAU,EAAvD;AACD;;AAEc,MAAMC,WAAN,CAAkB;AAC/B;AACF;AACA;AACA;AACA;AACEC,EAAAA,WAAW,CAACC,YAAD,EAAeC,UAAf,EAA2B;AACpC;AACA,SAAKC,KAAL,GAAa,uBAAUF,YAAV,CAAb;AACA,SAAKG,cAAL,GAAsB,IAAtB;AACA,SAAKC,QAAL,GAAgB,EAAhB;;AAEA,QAAIH,UAAJ,EAAgB;AACdA,MAAAA,UAAU,CAACI,KAAX,GAAmB,KAAnB;AACAJ,MAAAA,UAAU,CAACK,OAAX,GAAqB,EAArB;AACAL,MAAAA,UAAU,CAACC,KAAX,GAAmB,KAAKA,KAAxB;AACA,WAAKD,UAAL,GAAkBA,UAAlB;AACD;;AAED,QAAIM,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IAAyC,yBAA7C,EAA4D;AAC1D;AACA,UAAIC,GAAG,GAAG,8BAAV;AACA,UAAIT,UAAJ,EAAgBS,GAAG,IAAI,aAAP;AAChBC,MAAAA,OAAO,CAACC,cAAR,CAAuBF,GAAvB;AACAC,MAAAA,OAAO,CAACE,GAAR,CAAY,gBAAZ,EAA8B,uBAAUb,YAAV,CAA9B;AACAW,MAAAA,OAAO,CAACG,QAAR;AACA;A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AM,IAAI8B,KAAJ,CAAUpC,gBAAV,CAAN;AACrB,UAAM;AAAES,MAAAA;AAAF,QAAe,IAArB;;AACA,QAAIA,QAAQ,CAAC4B,OAAT,CAAiBF,QAAjB,IAA6B,CAAjC,EAAoC;AAClC1B,MAAAA,QAAQ,CAAC+B,IAAT,CAAcL,QAAd;AACD;AACF;;AAlI8B","sourcesContent":["import {\n cloneDeep,\n get,\n isArray,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport { isDebugMode } from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\n/**\n * Transform state path into the full path inside GlobalState object.\n * @param {string} statePath\n * @return {string}\n * @ignore\n */\nfunction fullPath(statePath) {\n return isNil(statePath) ? 'state' : `state.${statePath}`;\n}\n\nexport default class GlobalState {\n /**\n * Creates a new global state object.\n * @param {any} [initialState] Intial global state content.\n * @param {SsrContext} [ssrContext] Server-side rendering context.\n */\n constructor(initialState, ssrContext) {\n /* eslint-disable no-param-reassign */\n this.state = cloneDeep(initialState);\n this.nextNotifierId = null;\n this.watchers = [];\n\n if (ssrContext) {\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.state;\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeep(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n /* eslint-enable no-param-reassign */\n }\n\n /**\n * Gets the value at given `path` of global state. If `path` is null or\n * undefined, the entire state object is returned.\n * @param {string} [path] Dot-delimitered state path. If not given, entire\n * global state content is returned.\n * @return {any}\n */\n get(path) {\n return get(this, fullPath(path));\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param {string} [path] Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param {any} value The value.\n * @return {any} Given `value` itself.\n */\n set(path, value) {\n const p = fullPath(path);\n if (value !== get(this, p)) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState update. Path: \"${path || ''}\"`,\n );\n console.log('New value:', cloneDeep(value));\n /* eslint-enable no-console */\n }\n let pos = this;\n const pathSegments = toPath(p);\n for (let i = 0; i < pathSegments.length - 1; i += 1) {\n const seg = pathSegments[i];\n const next = pos[seg];\n if (isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else break;\n pos = pos[seg];\n }\n\n // TODO: With such naive use of _.set, the state is mutated in place,\n // which may cause tons of unexpected side effects for dependants.\n // It will be better to partially clone the state, so that any existing\n // references are not mutated, while the full deep clonning is also\n // avoided.\n set(this, p, value);\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.state;\n } else if (!this.nextNotifierId) {\n this.nextNotifierId = setTimeout(() => {\n this.nextNotifierId = null;\n [...this.watchers].forEach((w) => w());\n });\n }\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log('New state:', cloneDeep(this.state));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param {function} callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n const { watchers } = this;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1];\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param {function} callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n const { watchers } = this;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"file":"GlobalState.js"}
1
+ {"version":3,"file":"GlobalState.js","names":["ERR_NO_SSR_WATCH","GlobalState","initialState","nextNotifierId","ssrContext","currentState","watchers","constructor","dirty","pending","state","process","env","NODE_ENV","isDebugMode","msg","console","groupCollapsed","log","cloneDeep","groupEnd","get","path","initialValue","value","isNil","undefined","isFunction","set","root","segIdx","pos","pathSegments","toPath","length","seg","next","Array","isArray","isObject","slice","setTimeout","forEach","w","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.js"],"sourcesContent":["import {\n cloneDeep,\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport { isDebugMode } from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\nexport default class GlobalState {\n #initialState;\n\n #nextNotifierId = null;\n\n #ssrContext;\n\n #currentState;\n\n #watchers = [];\n\n /**\n * Creates a new global state object.\n * @param {any} [initialState] Intial global state content.\n * @param {SsrContext} [ssrContext] Server-side rendering context.\n */\n constructor(initialState, ssrContext) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.#ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeep(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * Allows to get the entire global state, and automatically set default value\n * at the \"path\".\n * @param {string} [path] Dot-delimitered state path. Pass it \"null\",\n * or \"undefined\" to refer the entire global state.\n * @param {object} [options={}] Additional options.\n * @param {boolean} [options.initialState] If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param {any} [options.initialValue] If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return {any} Retrieved value.\n */\n get(path, { initialState, initialValue } = {}) {\n const state = initialState ? this.#initialState : this.#currentState;\n let value = isNil(path) ? state : get(state, path);\n if (value === undefined && initialValue !== undefined) {\n value = isFunction(initialValue) ? initialValue() : initialValue;\n if (!initialState || this.get(path) === undefined) this.set(path, value);\n }\n return value;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param {string} [path] Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param {any} value The value.\n * @return {any} Given `value` itself.\n */\n set(path, value) {\n if (value !== this.get(path)) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState update. Path: \"${path || ''}\"`,\n );\n console.log('New value:', cloneDeep(value));\n /* eslint-enable no-console */\n }\n\n if (isNil(path)) this.#currentState = value;\n else {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx];\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]] = value;\n }\n\n this.#currentState = root.state;\n }\n\n if (this.#ssrContext) {\n this.#ssrContext.dirty = true;\n this.#ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = null;\n [...this.#watchers].forEach((w) => w());\n });\n }\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log('New state:', cloneDeep(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param {function} callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback) {\n if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1];\n watchers.pop();\n }\n }\n\n get ssrContext() { return this.#ssrContext; }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param {function} callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback) {\n if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;;;AAAA;;AAUA;;AAEA,MAAMA,gBAAgB,GAAG,gDAAzB;;AAEe,MAAMC,WAAN,CAAkB;EAC/B,CAACC,YAAD;EAEA,CAACC,cAAD,GAAkB,IAAlB;EAEA,CAACC,UAAD;EAEA,CAACC,YAAD;EAEA,CAACC,QAAD,GAAY,EAAZ;EAEA;AACF;AACA;AACA;AACA;;EACEC,WAAW,CAACL,YAAD,EAAeE,UAAf,EAA2B;IAC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ACyC,OAAT,CAAiBF,QAAjB,CAAZ;;IACA,IAAId,GAAG,IAAI,CAAX,EAAc;MACZzB,QAAQ,CAACyB,GAAD,CAAR,GAAgBzB,QAAQ,CAACA,QAAQ,CAAC4B,MAAT,GAAkB,CAAnB,CAAxB;MACA5B,QAAQ,CAAC0C,GAAT;IACD;EACF;;EAEa,IAAV5C,UAAU,GAAG;IAAE,OAAO,KAAK,CAACA,UAAb;EAA0B;EAE7C;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;EACE6C,KAAK,CAACJ,QAAD,EAAW;IACd,IAAI,KAAK,CAACzC,UAAV,EAAsB,MAAM,IAAI0C,KAAJ,CAAU9C,gBAAV,CAAN;IAEtB,MAAMM,QAAQ,GAAG,KAAK,CAACA,QAAvB;;IACA,IAAIA,QAAQ,CAACyC,OAAT,CAAiBF,QAAjB,IAA6B,CAAjC,EAAoC;MAClCvC,QAAQ,CAAC4C,IAAT,CAAcL,QAAd;IACD;EACF;;AAxK8B"}
@@ -86,18 +86,14 @@ function GlobalStateProvider({
86
86
  ssrContext,
87
87
  stateProxy
88
88
  }) {
89
- let state; // Here Rules of Hooks are violated because hooks are called conditionally,
90
- // however we assume that these properties should not change at runtime, thus
91
- // the actual hook order is preserved. Probably, it should be handled better,
92
- // though.
89
+ const state = (0, _react.useRef)();
93
90
 
94
- /* eslint-disable react-hooks/rules-of-hooks */
95
-
96
- if (stateProxy instanceof _GlobalState.default) state = stateProxy;else if (stateProxy) state = getGlobalState();else [state] = (0, _react.useState)(new _GlobalState.default(initialState, ssrContext));
97
- /* eslint-enable react-hooks/rules-of-hooks */
91
+ if (!state.current) {
92
+ if (stateProxy instanceof _GlobalState.default) state.current = stateProxy;else if (stateProxy) state.current = getGlobalState();else state.current = new _GlobalState.default(initialState, ssrContext);
93
+ }
98
94
 
99
95
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(context.Provider, {
100
- value: state,
96
+ value: state.current,
101
97
  children: children
102
98
  });
103
99
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/GlobalStateProvider.jsx"],"names":["context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","initialState","stateProxy","state","GlobalState"],"mappings":";;;;;;;;;;;AAEA;;AAEA;;;;AAJA;AAMA,MAAMA,OAAO,gBAAG,2BAAhB;AAEA;AACA;AACA;AACA;AACA;AACA;;AACO,SAASC,cAAT,GAA0B;AAC/B;AACA;AACA;AACA;AACA;;AACA;AACA,QAAMC,WAAW,GAAG,uBAAWF,OAAX,CAApB;AACA;;AACA,MAAI,CAACE,WAAL,EAAkB,MAAM,IAAIC,KAAJ,CAAU,6BAAV,CAAN;AAClB,SAAOD,WAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASE,aAAT,CAAuBC,sBAAsB,GAAG,IAAhD,EAAsD;AAC3D,QAAM;AAAEC,IAAAA;AAAF,MAAiBL,cAAc,EAArC;;AACA,MAAI,CAACK,UAAD,IAAeD,sBAAnB,EAA2C;AACzC,UAAM,IAAIF,KAAJ,CAAU,sBAAV,CAAN;AACD;;AACD,SAAOG,UAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACe,SAASC,mBAAT,CAA6B;AAC1CC,EAAAA,QAD0C;AAE1CC,EAAAA,YAF0C;AAG1CH,EAAAA,UAH0C;AAI1CI,EAAAA;AAJ0C,CAA7B,EAKZ;AACD,MAAIC,KAAJ,CADC,CAED;AACA;AACA;AACA;;AACA;;AACA,MAAID,UAAU,YAAYE,oBAA1B,EAAuCD,KAAK,GAAGD,UAAR,CAAvC,KACK,IAAIA,UAAJ,EAAgBC,KAAK,GAAGV,cAAc,EAAtB,CAAhB,KACA,CAACU,KAAD,IAAU,qBAAS,IAAIC,oBAAJ,CAAgBH,YAAhB,EAA8BH,UAA9B,CAAT,CAAV;AACL;;AACA,sBACE,qBAAC,OAAD,CAAS,QAAT;AAAkB,IAAA,KAAK,EAAEK,KAAzB;AAAA,cACGH;AADH,IADF;AAKD","sourcesContent":["/* eslint-disable react/prop-types */\n\nimport { createContext, useContext, useState } from 'react';\n\nimport GlobalState from './GlobalState';\n\nconst context = createContext();\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 {GlobalState}\n */\nexport function getGlobalState() {\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;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param {boolean} [throwWithoutSsrContext=true] 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 {SsrContext} 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(throwWithoutSsrContext = true) {\n const { ssrContext } = getGlobalState();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\n/**\n * Provides global state to its children.\n * @prop {ReactNode} [children] Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @prop {any} [initialState] Initial content of the global state.\n * @prop {SsrContext} [ssrContext] Server-side rendering (SSR) context.\n * @prop {boolean|GlobalState} [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 */\nexport default function GlobalStateProvider({\n children,\n initialState,\n ssrContext,\n stateProxy,\n}) {\n let state;\n // Here Rules of Hooks are violated because hooks are called conditionally,\n // however we assume that these properties should not change at runtime, thus\n // the actual hook order is preserved. Probably, it should be handled better,\n // though.\n /* eslint-disable react-hooks/rules-of-hooks */\n if (stateProxy instanceof GlobalState) state = stateProxy;\n else if (stateProxy) state = getGlobalState();\n else [state] = useState(new GlobalState(initialState, ssrContext));\n /* eslint-enable react-hooks/rules-of-hooks */\n return (\n <context.Provider value={state}>\n {children}\n </context.Provider>\n );\n}\n"],"file":"GlobalStateProvider.js"}
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["context","createContext","getGlobalState","globalState","useContext","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","initialState","stateProxy","state","useRef","current","GlobalState"],"sources":["../../src/GlobalStateProvider.jsx"],"sourcesContent":["/* eslint-disable react/prop-types */\n\nimport { createContext, useContext, useRef } from 'react';\n\nimport GlobalState from './GlobalState';\n\nconst context = createContext();\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 {GlobalState}\n */\nexport function getGlobalState() {\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;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param {boolean} [throwWithoutSsrContext=true] 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 {SsrContext} 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(throwWithoutSsrContext = true) {\n const { ssrContext } = getGlobalState();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\n/**\n * Provides global state to its children.\n * @prop {ReactNode} [children] Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @prop {any} [initialState] Initial content of the global state.\n * @prop {SsrContext} [ssrContext] Server-side rendering (SSR) context.\n * @prop {boolean|GlobalState} [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 */\nexport default function GlobalStateProvider({\n children,\n initialState,\n ssrContext,\n stateProxy,\n}) {\n const state = useRef();\n if (!state.current) {\n if (stateProxy instanceof GlobalState) state.current = stateProxy;\n else if (stateProxy) state.current = getGlobalState();\n else state.current = new GlobalState(initialState, ssrContext);\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AAEA;;AAEA;;;;AAJA;AAMA,MAAMA,OAAO,gBAAG,IAAAC,oBAAA,GAAhB;AAEA;AACA;AACA;AACA;AACA;AACA;;AACO,SAASC,cAAT,GAA0B;EAC/B;EACA;EACA;EACA;EACA;;EACA;EACA,MAAMC,WAAW,GAAG,IAAAC,iBAAA,EAAWJ,OAAX,CAApB;EACA;;EACA,IAAI,CAACG,WAAL,EAAkB,MAAM,IAAIE,KAAJ,CAAU,6BAAV,CAAN;EAClB,OAAOF,WAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASG,aAAT,CAAuBC,sBAAsB,GAAG,IAAhD,EAAsD;EAC3D,MAAM;IAAEC;EAAF,IAAiBN,cAAc,EAArC;;EACA,IAAI,CAACM,UAAD,IAAeD,sBAAnB,EAA2C;IACzC,MAAM,IAAIF,KAAJ,CAAU,sBAAV,CAAN;EACD;;EACD,OAAOG,UAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACe,SAASC,mBAAT,CAA6B;EAC1CC,QAD0C;EAE1CC,YAF0C;EAG1CH,UAH0C;EAI1CI;AAJ0C,CAA7B,EAKZ;EACD,MAAMC,KAAK,GAAG,IAAAC,aAAA,GAAd;;EACA,IAAI,CAACD,KAAK,CAACE,OAAX,EAAoB;IAClB,IAAIH,UAAU,YAAYI,oBAA1B,EAAuCH,KAAK,CAACE,OAAN,GAAgBH,UAAhB,CAAvC,KACK,IAAIA,UAAJ,EAAgBC,KAAK,CAACE,OAAN,GAAgBb,cAAc,EAA9B,CAAhB,KACAW,KAAK,CAACE,OAAN,GAAgB,IAAIC,oBAAJ,CAAgBL,YAAhB,EAA8BH,UAA9B,CAAhB;EACN;;EACD,oBACE,qBAAC,OAAD,CAAS,QAAT;IAAkB,KAAK,EAAEK,KAAK,CAACE,OAA/B;IAAA,UACGL;EADH,EADF;AAKD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.js"],"names":["Promise","allSettled","promises","all","map","p","finally"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;;AAMA;;AACA;;AACA;;;;;;AAlBA;AACA;AACA;AACA;AACA,IAAI,CAACA,OAAO,CAACC,UAAb,EAAyB;AACvBD,EAAAA,OAAO,CAACC,UAAR,GAAsBC,QAAD,IAAcF,OAAO,CAACG,GAAR,CACjCD,QAAQ,CAACE,GAAT,CAAcC,CAAD,IAAQA,CAAC,YAAYL,OAAb,GAAuBK,CAAC,CAACC,OAAF,CAAU,MAAM,IAAhB,CAAvB,GAA+CD,CAApE,CADiC,CAAnC;AAGD","sourcesContent":["// TODO: This is a temporary polyfill for `Promise.allSettled(..)` method,\n// which is supported natively by NodeJS >= v12.9.0. As earlier NodeJS version\n// are still in a wide use, this polyfill is added here, and it is to be dropped\n// some time later.\nif (!Promise.allSettled) {\n Promise.allSettled = (promises) => Promise.all(\n promises.map((p) => (p instanceof Promise ? p.finally(() => null) : p)),\n );\n}\n\nexport {\n default as GlobalStateProvider,\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nexport { default as useAsyncCollection } from './useAsyncCollection';\nexport { default as useAsyncData } from './useAsyncData';\nexport { default as useGlobalState } from './useGlobalState';\n"],"file":"index.js"}
1
+ {"version":3,"file":"index.js","names":["Promise","allSettled","promises","all","map","p","finally"],"sources":["../../src/index.js"],"sourcesContent":["// TODO: This is a temporary polyfill for `Promise.allSettled(..)` method,\n// which is supported natively by NodeJS >= v12.9.0. As earlier NodeJS version\n// are still in a wide use, this polyfill is added here, and it is to be dropped\n// some time later.\nif (!Promise.allSettled) {\n Promise.allSettled = (promises) => Promise.all(\n promises.map((p) => (p instanceof Promise ? p.finally(() => null) : p)),\n );\n}\n\nexport {\n default as GlobalStateProvider,\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nexport { default as useAsyncCollection } from './useAsyncCollection';\nexport { default as useAsyncData } from './useAsyncData';\nexport { default as useGlobalState } from './useGlobalState';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;;AAMA;;AACA;;AACA;;;;;;AAlBA;AACA;AACA;AACA;AACA,IAAI,CAACA,OAAO,CAACC,UAAb,EAAyB;EACvBD,OAAO,CAACC,UAAR,GAAsBC,QAAD,IAAcF,OAAO,CAACG,GAAR,CACjCD,QAAQ,CAACE,GAAT,CAAcC,CAAD,IAAQA,CAAC,YAAYL,OAAb,GAAuBK,CAAC,CAACC,OAAF,CAAU,MAAM,IAAhB,CAAvB,GAA+CD,CAApE,CADiC,CAAnC;AAGD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/useAsyncCollection.js"],"names":["useAsyncCollection","id","path","loader","options","itemPath","oldData"],"mappings":";;;;;;;;;AAIA;;AAJA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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,kBAAT,CACbC,EADa,EAEbC,IAFa,EAGbC,MAHa,EAIbC,OAAO,GAAG,EAJG,EAKb;AACA,QAAMC,QAAQ,GAAGH,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAjB,GAAqBA,EAA1C;AACA,SAAO,2BAAaI,QAAb,EAAwBC,OAAD,IAAaH,MAAM,CAACF,EAAD,EAAKK,OAAL,CAA1C,EAAyDF,OAAzD,CAAP;AACD","sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData from './useAsyncData';\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param {string} id ID of the collection item to load & use.\n * @param {string} path The global state path where entire collection should be\n * stored.\n * @param {AsyncCollectionLoader} loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\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 useAsyncCollection(\n id,\n path,\n loader,\n options = {},\n) {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData(itemPath, (oldData) => loader(id, oldData), options);\n}\n"],"file":"useAsyncCollection.js"}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["useAsyncCollection","id","path","loader","options","itemPath","useAsyncData","oldData"],"sources":["../../src/useAsyncCollection.js"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData from './useAsyncData';\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param {string} id ID of the collection item to load & use.\n * @param {string} path The global state path where entire collection should be\n * stored.\n * @param {AsyncCollectionLoader} loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\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 useAsyncCollection(\n id,\n path,\n loader,\n options = {},\n) {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData(itemPath, (oldData) => loader(id, oldData), options);\n}\n"],"mappings":";;;;;;;;;AAIA;;AAJA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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,kBAAT,CACbC,EADa,EAEbC,IAFa,EAGbC,MAHa,EAIbC,OAAO,GAAG,EAJG,EAKb;EACA,MAAMC,QAAQ,GAAGH,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAjB,GAAqBA,EAA1C;EACA,OAAO,IAAAK,qBAAA,EAAaD,QAAb,EAAwBE,OAAD,IAAaJ,MAAM,CAACF,EAAD,EAAKM,OAAL,CAA1C,EAAyDH,OAAzD,CAAP;AACD"}
@@ -138,17 +138,14 @@ function useAsyncData(path, loader, options = {}) {
138
138
  // because that way we'll have issues with SSR (see details below).
139
139
 
140
140
  const globalState = (0, _GlobalStateProvider.getGlobalState)();
141
- let state = globalState.get(path);
142
-
143
- if (state === undefined) {
144
- state = {
141
+ const state = globalState.get(path, {
142
+ initialValue: {
145
143
  data: null,
146
144
  numRefs: 0,
147
145
  operationId: '',
148
146
  timestamp: 0
149
- };
150
- globalState.set(path, state);
151
- }
147
+ }
148
+ });
152
149
 
153
150
  if (globalState.ssrContext && !options.noSSR) {
154
151
  if (!state.timestamp && !state.operationId) {
@@ -205,14 +202,14 @@ function useAsyncData(path, loader, options = {}) {
205
202
  // eslint-disable-line react-hooks/rules-of-hooks
206
203
  if (!loadTriggered && deps.length) load(path, loader, globalState);
207
204
  }, deps); // eslint-disable-line react-hooks/exhaustive-deps
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
-
205
+ }
214
206
 
215
- const [localState] = (0, _useGlobalState.default)(path);
207
+ const [localState] = (0, _useGlobalState.default)(path, {
208
+ data: null,
209
+ numRefs: 0,
210
+ operationId: '',
211
+ timestamp: 0
212
+ });
216
213
  return {
217
214
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
218
215
  loading: Boolean(localState.operationId),