@dr.pogodin/react-global-state 0.8.3 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/module/GlobalState.js +156 -146
- package/build/module/GlobalState.js.map +1 -1
- package/build/module/GlobalStateProvider.js +21 -36
- package/build/module/GlobalStateProvider.js.map +1 -1
- package/build/module/index.js +1 -8
- package/build/module/index.js.map +1 -1
- package/build/module/useAsyncCollection.js +5 -6
- package/build/module/useAsyncCollection.js.map +1 -1
- package/build/module/useAsyncData.js +75 -117
- package/build/module/useAsyncData.js.map +1 -1
- package/build/module/useGlobalState.js +41 -64
- package/build/module/useGlobalState.js.map +1 -1
- package/build/module/utils.js.map +1 -1
- package/build/node/GlobalState.js +83 -81
- package/build/node/GlobalState.js.map +1 -1
- package/build/node/GlobalStateProvider.js +9 -25
- package/build/node/GlobalStateProvider.js.map +1 -1
- package/build/node/index.js +0 -8
- package/build/node/index.js.map +1 -1
- package/build/node/useAsyncCollection.js +0 -3
- package/build/node/useAsyncCollection.js.map +1 -1
- package/build/node/useAsyncData.js +25 -36
- package/build/node/useAsyncData.js.map +1 -1
- package/build/node/useGlobalState.js +36 -54
- package/build/node/useGlobalState.js.map +1 -1
- package/build/node/utils.js +0 -2
- package/build/node/utils.js.map +1 -1
- package/package.json +21 -21
|
@@ -4,42 +4,33 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
6
|
exports.default = void 0;
|
|
7
|
-
|
|
8
7
|
var _lodash = require("lodash");
|
|
9
|
-
|
|
10
8
|
var _utils = require("./utils");
|
|
11
|
-
|
|
12
9
|
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
|
-
|
|
24
10
|
class GlobalState {
|
|
11
|
+
#initialState;
|
|
12
|
+
#nextNotifierId = null;
|
|
13
|
+
#ssrContext;
|
|
14
|
+
#currentState;
|
|
15
|
+
#watchers = [];
|
|
16
|
+
|
|
25
17
|
/**
|
|
26
18
|
* Creates a new global state object.
|
|
27
19
|
* @param {any} [initialState] Intial global state content.
|
|
28
20
|
* @param {SsrContext} [ssrContext] Server-side rendering context.
|
|
29
21
|
*/
|
|
30
22
|
constructor(initialState, ssrContext) {
|
|
31
|
-
|
|
32
|
-
this
|
|
33
|
-
this.nextNotifierId = null;
|
|
34
|
-
this.watchers = [];
|
|
35
|
-
|
|
23
|
+
this.#currentState = initialState;
|
|
24
|
+
this.#initialState = initialState;
|
|
36
25
|
if (ssrContext) {
|
|
26
|
+
/* eslint-disable no-param-reassign */
|
|
37
27
|
ssrContext.dirty = false;
|
|
38
28
|
ssrContext.pending = [];
|
|
39
|
-
ssrContext.state = this
|
|
40
|
-
|
|
41
|
-
}
|
|
29
|
+
ssrContext.state = this.#currentState;
|
|
30
|
+
/* eslint-enable no-param-reassign */
|
|
42
31
|
|
|
32
|
+
this.#ssrContext = ssrContext;
|
|
33
|
+
}
|
|
43
34
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
44
35
|
/* eslint-disable no-console */
|
|
45
36
|
let msg = 'New ReactGlobalState created';
|
|
@@ -49,21 +40,36 @@ class GlobalState {
|
|
|
49
40
|
console.groupEnd();
|
|
50
41
|
/* eslint-enable no-console */
|
|
51
42
|
}
|
|
52
|
-
/* eslint-enable no-param-reassign */
|
|
53
|
-
|
|
54
43
|
}
|
|
44
|
+
|
|
55
45
|
/**
|
|
56
|
-
* Gets
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
46
|
+
* Gets current or initial value at the specified "path" of the global state.
|
|
47
|
+
* Allows to get the entire global state, and automatically set default value
|
|
48
|
+
* at the "path".
|
|
49
|
+
* @param {string} [path] Dot-delimitered state path. Pass it "null",
|
|
50
|
+
* or "undefined" to refer the entire global state.
|
|
51
|
+
* @param {object} [options={}] Additional options.
|
|
52
|
+
* @param {boolean} [options.initialState] If "true" the value will be read
|
|
53
|
+
* from the initial state instead of the current one.
|
|
54
|
+
* @param {any} [options.initialValue] If the value read from the "path" is
|
|
55
|
+
* "undefined", this "initialValue" will be returned instead. In such case
|
|
56
|
+
* "initialValue" will also be written to the "path" of the current global
|
|
57
|
+
* state (no matter "initialState" flag), if "undefined" is stored there.
|
|
58
|
+
* @return {any} Retrieved value.
|
|
61
59
|
*/
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
60
|
+
get(path, {
|
|
61
|
+
initialState,
|
|
62
|
+
initialValue
|
|
63
|
+
} = {}) {
|
|
64
|
+
const state = initialState ? this.#initialState : this.#currentState;
|
|
65
|
+
let value = (0, _lodash.isNil)(path) ? state : (0, _lodash.get)(state, path);
|
|
66
|
+
if (value === undefined && initialValue !== undefined) {
|
|
67
|
+
value = (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue;
|
|
68
|
+
if (!initialState || this.get(path) === undefined) this.set(path, value);
|
|
69
|
+
}
|
|
70
|
+
return value;
|
|
66
71
|
}
|
|
72
|
+
|
|
67
73
|
/**
|
|
68
74
|
* Writes the `value` to given global state `path`.
|
|
69
75
|
* @param {string} [path] Dot-delimitered state path. If not given, entire
|
|
@@ -71,12 +77,8 @@ class GlobalState {
|
|
|
71
77
|
* @param {any} value The value.
|
|
72
78
|
* @return {any} Given `value` itself.
|
|
73
79
|
*/
|
|
74
|
-
|
|
75
|
-
|
|
76
80
|
set(path, value) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (value !== (0, _lodash.get)(this, p)) {
|
|
81
|
+
if (value !== this.get(path)) {
|
|
80
82
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
81
83
|
/* eslint-disable no-console */
|
|
82
84
|
console.groupCollapsed(`ReactGlobalState update. Path: "${path || ''}"`);
|
|
@@ -84,37 +86,44 @@ class GlobalState {
|
|
|
84
86
|
/* eslint-enable no-console */
|
|
85
87
|
}
|
|
86
88
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
89
|
+
if ((0, _lodash.isNil)(path)) this.#currentState = value;else {
|
|
90
|
+
const root = {
|
|
91
|
+
state: this.#currentState
|
|
92
|
+
};
|
|
93
|
+
let segIdx = 0;
|
|
94
|
+
let pos = root;
|
|
95
|
+
const pathSegments = (0, _lodash.toPath)(`state.${path}`);
|
|
96
|
+
for (; segIdx < pathSegments.length - 1; segIdx += 1) {
|
|
97
|
+
const seg = pathSegments[segIdx];
|
|
98
|
+
const next = pos[seg];
|
|
99
|
+
if (Array.isArray(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = {
|
|
100
|
+
...next
|
|
101
|
+
};else {
|
|
102
|
+
// We arrived to a state sub-segment, where the remaining part of
|
|
103
|
+
// the update path does not exist yet. We rely on lodash's set()
|
|
104
|
+
// function to create the remaining path, and set the value.
|
|
105
|
+
(0, _lodash.set)(pos, pathSegments.slice(segIdx), value);
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
pos = pos[seg];
|
|
109
|
+
}
|
|
110
|
+
if (segIdx === pathSegments.length - 1) {
|
|
111
|
+
pos[pathSegments[segIdx]] = value;
|
|
112
|
+
}
|
|
113
|
+
this.#currentState = root.state;
|
|
114
|
+
}
|
|
115
|
+
if (this.#ssrContext) {
|
|
116
|
+
this.#ssrContext.dirty = true;
|
|
117
|
+
this.#ssrContext.state = this.#currentState;
|
|
118
|
+
} else if (!this.#nextNotifierId) {
|
|
119
|
+
this.#nextNotifierId = setTimeout(() => {
|
|
120
|
+
this.#nextNotifierId = null;
|
|
121
|
+
[...this.#watchers].forEach(w => w());
|
|
112
122
|
});
|
|
113
123
|
}
|
|
114
|
-
|
|
115
124
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
116
125
|
/* eslint-disable no-console */
|
|
117
|
-
console.log('New state:', (0, _lodash.cloneDeep)(this
|
|
126
|
+
console.log('New state:', (0, _lodash.cloneDeep)(this.#currentState));
|
|
118
127
|
console.groupEnd();
|
|
119
128
|
/* eslint-enable no-console */
|
|
120
129
|
}
|
|
@@ -122,6 +131,7 @@ class GlobalState {
|
|
|
122
131
|
|
|
123
132
|
return value;
|
|
124
133
|
}
|
|
134
|
+
|
|
125
135
|
/**
|
|
126
136
|
* Unsubscribes `callback` from watching state updates; no operation if
|
|
127
137
|
* `callback` is not subscribed to the state updates.
|
|
@@ -129,20 +139,19 @@ class GlobalState {
|
|
|
129
139
|
* @throws if {@link SsrContext} is attached to the state instance: the state
|
|
130
140
|
* watching functionality is intended for client-side (non-SSR) only.
|
|
131
141
|
*/
|
|
132
|
-
|
|
133
|
-
|
|
134
142
|
unWatch(callback) {
|
|
135
|
-
if (this
|
|
136
|
-
const
|
|
137
|
-
watchers
|
|
138
|
-
} = this;
|
|
143
|
+
if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);
|
|
144
|
+
const watchers = this.#watchers;
|
|
139
145
|
const pos = watchers.indexOf(callback);
|
|
140
|
-
|
|
141
146
|
if (pos >= 0) {
|
|
142
147
|
watchers[pos] = watchers[watchers.length - 1];
|
|
143
148
|
watchers.pop();
|
|
144
149
|
}
|
|
145
150
|
}
|
|
151
|
+
get ssrContext() {
|
|
152
|
+
return this.#ssrContext;
|
|
153
|
+
}
|
|
154
|
+
|
|
146
155
|
/**
|
|
147
156
|
* Subscribes `callback` to watch state updates; no operation if
|
|
148
157
|
* `callback` is already subscribed to this state instance.
|
|
@@ -153,20 +162,13 @@ class GlobalState {
|
|
|
153
162
|
* @throws if {@link SsrContext} is attached to the state instance: the state
|
|
154
163
|
* watching functionality is intended for client-side (non-SSR) only.
|
|
155
164
|
*/
|
|
156
|
-
|
|
157
|
-
|
|
158
165
|
watch(callback) {
|
|
159
|
-
if (this
|
|
160
|
-
const
|
|
161
|
-
watchers
|
|
162
|
-
} = this;
|
|
163
|
-
|
|
166
|
+
if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);
|
|
167
|
+
const watchers = this.#watchers;
|
|
164
168
|
if (watchers.indexOf(callback) < 0) {
|
|
165
169
|
watchers.push(callback);
|
|
166
170
|
}
|
|
167
171
|
}
|
|
168
|
-
|
|
169
172
|
}
|
|
170
|
-
|
|
171
173
|
exports.default = GlobalState;
|
|
172
174
|
//# sourceMappingURL=GlobalState.js.map
|
|
@@ -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,C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,EAA0B,uBAAU,KAAKX,KAAf,CAA1B;AACAS,QAAAA,OAAO,CAACG,QAAR;AACA;AACD;AACF;;AACD,WAAOI,KAAP;AACD;AAED;AACF;AACA;AACA;AACA;AACA;AACA;;;AACEW,EAAAA,OAAO,CAACC,QAAD,EAAW;AAChB,QAAI,KAAK7B,UAAT,EAAqB,MAAM,IAAI8B,KAAJ,CAAUpC,gBAAV,CAAN;AACrB,UAAM;AAAES,MAAAA;AAAF,QAAe,IAArB;AACA,UAAMgB,GAAG,GAAGhB,QAAQ,CAAC4B,OAAT,CAAiBF,QAAjB,CAAZ;;AACA,QAAIV,GAAG,IAAI,CAAX,EAAc;AACZhB,MAAAA,QAAQ,CAACgB,GAAD,CAAR,GAAgBhB,QAAQ,CAACA,QAAQ,CAACmB,MAAT,GAAkB,CAAnB,CAAxB;AACAnB,MAAAA,QAAQ,CAAC6B,GAAT;AACD;AACF;AAED;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACEC,EAAAA,KAAK,CAACJ,QAAD,EAAW;AACd,QAAI,KAAK7B,UAAT,EAAqB,MAAM,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,gDAAgD;AAE1D,MAAMC,WAAW,CAAC;EAC/B,CAACC,YAAY;EAEb,CAACC,cAAc,GAAG,IAAI;EAEtB,CAACC,UAAU;EAEX,CAACC,YAAY;EAEb,CAACC,QAAQ,GAAG,EAAE;;EAEd;AACF;AACA;AACA;AACA;EACEC,WAAW,CAACL,YAAY,EAAEE,UAAU,EAAE;IACpC,IAAI,CAAC,CAACC,YAAY,GAAGH,YAAY;IACjC,IAAI,CAAC,CAACA,YAAY,GAAGA,YAAY;IAEjC,IAAIE,UAAU,EAAE;MACd;MACAA,UAAU,CAACI,KAAK,GAAG,KAAK;MACxBJ,UAAU,CAACK,OAAO,GAAG,EAAE;MACvBL,UAAU,CAACM,KAAK,GAAG,IAAI,CAAC,CAACL,YAAY;MACrC;;MAEA,IAAI,CAAC,CAACD,UAAU,GAAGA,UAAU;IAC/B;IAEA,IAAIO,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,GAAE,EAAE;MAC1D;MACA,IAAIC,GAAG,GAAG,8BAA8B;MACxC,IAAIX,UAAU,EAAEW,GAAG,IAAI,aAAa;MACpCC,OAAO,CAACC,cAAc,CAACF,GAAG,CAAC;MAC3BC,OAAO,CAACE,GAAG,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,MAAM,IAAI0C,KAAK,CAAC9C,gBAAgB,CAAC;IAEvD,MAAMM,QAAQ,GAAG,IAAI,CAAC,CAACA,QAAQ;IAC/B,IAAIA,QAAQ,CAACyC,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClCvC,QAAQ,CAAC4C,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF;AAAC"}
|
|
@@ -1,43 +1,38 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
|
-
|
|
5
4
|
Object.defineProperty(exports, "__esModule", {
|
|
6
5
|
value: true
|
|
7
6
|
});
|
|
8
7
|
exports.default = GlobalStateProvider;
|
|
9
8
|
exports.getGlobalState = getGlobalState;
|
|
10
9
|
exports.getSsrContext = getSsrContext;
|
|
11
|
-
|
|
12
10
|
var _react = require("react");
|
|
13
|
-
|
|
14
11
|
var _GlobalState = _interopRequireDefault(require("./GlobalState"));
|
|
15
|
-
|
|
16
12
|
var _jsxRuntime = require("react/jsx-runtime");
|
|
17
|
-
|
|
18
13
|
/* eslint-disable react/prop-types */
|
|
14
|
+
|
|
19
15
|
const context = /*#__PURE__*/(0, _react.createContext)();
|
|
16
|
+
|
|
20
17
|
/**
|
|
21
18
|
* Gets {@link GlobalState} instance from the context. In most cases
|
|
22
19
|
* you should use {@link useGlobalState}, and other hooks to interact with
|
|
23
20
|
* the global state, instead of accessing it directly.
|
|
24
21
|
* @return {GlobalState}
|
|
25
22
|
*/
|
|
26
|
-
|
|
27
23
|
function getGlobalState() {
|
|
28
24
|
// Here Rules of Hooks are violated because "getGlobalState()" does not follow
|
|
29
25
|
// convention that hook names should start with use... This is intentional in
|
|
30
26
|
// our case, as getGlobalState() hook is intended for advance scenarious,
|
|
31
27
|
// while the normal interaction with the global state should happen via
|
|
32
28
|
// another hook, useGlobalState().
|
|
33
|
-
|
|
34
29
|
/* eslint-disable react-hooks/rules-of-hooks */
|
|
35
30
|
const globalState = (0, _react.useContext)(context);
|
|
36
31
|
/* eslint-enable react-hooks/rules-of-hooks */
|
|
37
|
-
|
|
38
32
|
if (!globalState) throw new Error('Missing GlobalStateProvider');
|
|
39
33
|
return globalState;
|
|
40
34
|
}
|
|
35
|
+
|
|
41
36
|
/**
|
|
42
37
|
* @category Hooks
|
|
43
38
|
* @desc Gets SSR context.
|
|
@@ -52,19 +47,16 @@ function getGlobalState() {
|
|
|
52
47
|
* - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
|
|
53
48
|
* to the global state provided by {@link <GlobalStateProvider>}.
|
|
54
49
|
*/
|
|
55
|
-
|
|
56
|
-
|
|
57
50
|
function getSsrContext(throwWithoutSsrContext = true) {
|
|
58
51
|
const {
|
|
59
52
|
ssrContext
|
|
60
53
|
} = getGlobalState();
|
|
61
|
-
|
|
62
54
|
if (!ssrContext && throwWithoutSsrContext) {
|
|
63
55
|
throw new Error('No SSR context found');
|
|
64
56
|
}
|
|
65
|
-
|
|
66
57
|
return ssrContext;
|
|
67
58
|
}
|
|
59
|
+
|
|
68
60
|
/**
|
|
69
61
|
* Provides global state to its children.
|
|
70
62
|
* @prop {ReactNode} [children] Component children, which will be provided with
|
|
@@ -78,26 +70,18 @@ function getSsrContext(throwWithoutSsrContext = true) {
|
|
|
78
70
|
* - If `GlobalState` instance, it will be used by this provider.
|
|
79
71
|
* - If not given, a new `GlobalState` instance will be created and used.
|
|
80
72
|
*/
|
|
81
|
-
|
|
82
|
-
|
|
83
73
|
function GlobalStateProvider({
|
|
84
74
|
children,
|
|
85
75
|
initialState,
|
|
86
76
|
ssrContext,
|
|
87
77
|
stateProxy
|
|
88
78
|
}) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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 */
|
|
98
|
-
|
|
79
|
+
const state = (0, _react.useRef)();
|
|
80
|
+
if (!state.current) {
|
|
81
|
+
if (stateProxy instanceof _GlobalState.default) state.current = stateProxy;else if (stateProxy) state.current = getGlobalState();else state.current = new _GlobalState.default(initialState, ssrContext);
|
|
82
|
+
}
|
|
99
83
|
return /*#__PURE__*/(0, _jsxRuntime.jsx)(context.Provider, {
|
|
100
|
-
value: state,
|
|
84
|
+
value: state.current,
|
|
101
85
|
children: children
|
|
102
86
|
});
|
|
103
87
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
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 <GlobalStateProvider>} (hence the state) is missing.\n * @returns {SsrContext} SSR context.\n * @throws\n * - If current component has no parent {@link <GlobalStateProvider>}\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 <GlobalStateProvider>}.\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;AAAwC;AAJxC;;AAMA,MAAMA,OAAO,gBAAG,IAAAC,oBAAa,GAAE;;AAE/B;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,cAAc,GAAG;EAC/B;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAG,IAAAC,iBAAU,EAACJ,OAAO,CAAC;EACvC;EACA,IAAI,CAACG,WAAW,EAAE,MAAM,IAAIE,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOF,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,aAAa,CAACC,sBAAsB,GAAG,IAAI,EAAE;EAC3D,MAAM;IAAEC;EAAW,CAAC,GAAGN,cAAc,EAAE;EACvC,IAAI,CAACM,UAAU,IAAID,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOG,UAAU;AACnB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASC,mBAAmB,CAAC;EAC1CC,QAAQ;EACRC,YAAY;EACZH,UAAU;EACVI;AACF,CAAC,EAAE;EACD,MAAMC,KAAK,GAAG,IAAAC,aAAM,GAAE;EACtB,IAAI,CAACD,KAAK,CAACE,OAAO,EAAE;IAClB,IAAIH,UAAU,YAAYI,oBAAW,EAAEH,KAAK,CAACE,OAAO,GAAGH,UAAU,CAAC,KAC7D,IAAIA,UAAU,EAAEC,KAAK,CAACE,OAAO,GAAGb,cAAc,EAAE,CAAC,KACjDW,KAAK,CAACE,OAAO,GAAG,IAAIC,oBAAW,CAACL,YAAY,EAAEH,UAAU,CAAC;EAChE;EACA,oBACE,qBAAC,OAAO,CAAC,QAAQ;IAAC,KAAK,EAAEK,KAAK,CAACE,OAAQ;IAAA,UACpCL;EAAQ,EACQ;AAEvB"}
|
package/build/node/index.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
|
-
|
|
5
4
|
Object.defineProperty(exports, "__esModule", {
|
|
6
5
|
value: true
|
|
7
6
|
});
|
|
@@ -41,19 +40,12 @@ Object.defineProperty(exports, "useGlobalState", {
|
|
|
41
40
|
return _useGlobalState.default;
|
|
42
41
|
}
|
|
43
42
|
});
|
|
44
|
-
|
|
45
43
|
var _GlobalStateProvider = _interopRequireWildcard(require("./GlobalStateProvider"));
|
|
46
|
-
|
|
47
44
|
var _useAsyncCollection = _interopRequireDefault(require("./useAsyncCollection"));
|
|
48
|
-
|
|
49
45
|
var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
|
|
50
|
-
|
|
51
46
|
var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
|
|
52
|
-
|
|
53
47
|
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
|
|
54
|
-
|
|
55
48
|
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
|
|
56
|
-
|
|
57
49
|
// TODO: This is a temporary polyfill for `Promise.allSettled(..)` method,
|
|
58
50
|
// which is supported natively by NodeJS >= v12.9.0. As earlier NodeJS version
|
|
59
51
|
// are still in a wide use, this polyfill is added here, and it is to be dropped
|
package/build/node/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
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;AAA6D;AAAA;AAlB7D;AACA;AACA;AACA;AACA,IAAI,CAACA,OAAO,CAACC,UAAU,EAAE;EACvBD,OAAO,CAACC,UAAU,GAAIC,QAAQ,IAAKF,OAAO,CAACG,GAAG,CAC5CD,QAAQ,CAACE,GAAG,CAAEC,CAAC,IAAMA,CAAC,YAAYL,OAAO,GAAGK,CAAC,CAACC,OAAO,CAAC,MAAM,IAAI,CAAC,GAAGD,CAAE,CAAC,CACxE;AACH"}
|
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
|
-
|
|
5
4
|
Object.defineProperty(exports, "__esModule", {
|
|
6
5
|
value: true
|
|
7
6
|
});
|
|
8
7
|
exports.default = useAsyncCollection;
|
|
9
|
-
|
|
10
8
|
var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
|
|
11
|
-
|
|
12
9
|
/**
|
|
13
10
|
* Loads and uses an item in an async collection.
|
|
14
11
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
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,kBAAkB,CACxCC,EAAE,EACFC,IAAI,EACJC,MAAM,EACNC,OAAO,GAAG,CAAC,CAAC,EACZ;EACA,MAAMC,QAAQ,GAAGH,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAO,IAAAK,qBAAY,EAACD,QAAQ,EAAGE,OAAO,IAAKJ,MAAM,CAACF,EAAE,EAAEM,OAAO,CAAC,EAAEH,OAAO,CAAC;AAC1E"}
|