@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
|
@@ -1,27 +1,20 @@
|
|
|
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 = useAsyncData;
|
|
9
|
-
|
|
10
8
|
var _lodash = require("lodash");
|
|
11
|
-
|
|
12
9
|
var _react = require("react");
|
|
13
|
-
|
|
14
10
|
var _uuid = require("uuid");
|
|
15
|
-
|
|
16
11
|
var _GlobalStateProvider = require("./GlobalStateProvider");
|
|
17
|
-
|
|
18
12
|
var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
|
|
19
|
-
|
|
20
13
|
var _utils = require("./utils");
|
|
21
|
-
|
|
22
14
|
/**
|
|
23
15
|
* Loads and uses async data into the GlobalState path.
|
|
24
16
|
*/
|
|
17
|
+
|
|
25
18
|
const DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.
|
|
26
19
|
|
|
27
20
|
/**
|
|
@@ -38,7 +31,6 @@ const DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.
|
|
|
38
31
|
* @return {Promise} Resolves once the operation is done.
|
|
39
32
|
* @ignore
|
|
40
33
|
*/
|
|
41
|
-
|
|
42
34
|
async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
|
|
43
35
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
44
36
|
/* eslint-disable no-console */
|
|
@@ -51,7 +43,6 @@ async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
|
|
|
51
43
|
globalState.set(operationIdPath, operationId);
|
|
52
44
|
const data = await loader(oldData || globalState.get(path).data);
|
|
53
45
|
const state = globalState.get(path);
|
|
54
|
-
|
|
55
46
|
if (operationId === state.operationId) {
|
|
56
47
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
57
48
|
/* eslint-disable no-console */
|
|
@@ -60,12 +51,12 @@ async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
|
|
|
60
51
|
/* eslint-enable no-console */
|
|
61
52
|
}
|
|
62
53
|
|
|
63
|
-
globalState.set(path, {
|
|
54
|
+
globalState.set(path, {
|
|
55
|
+
...state,
|
|
64
56
|
data,
|
|
65
57
|
operationId: '',
|
|
66
58
|
timestamp: Date.now()
|
|
67
59
|
});
|
|
68
|
-
|
|
69
60
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
70
61
|
/* eslint-disable no-console */
|
|
71
62
|
console.groupEnd();
|
|
@@ -73,6 +64,7 @@ async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
|
|
|
73
64
|
}
|
|
74
65
|
}
|
|
75
66
|
}
|
|
67
|
+
|
|
76
68
|
/**
|
|
77
69
|
* Resolves asynchronous data, and stores them at given `path` of global
|
|
78
70
|
* state. When multiple components rely on asynchronous data at the same `path`,
|
|
@@ -124,8 +116,6 @@ async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
|
|
|
124
116
|
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
125
117
|
* `useAsyncData()` hooks logic.
|
|
126
118
|
*/
|
|
127
|
-
|
|
128
|
-
|
|
129
119
|
function useAsyncData(path, loader, options = {}) {
|
|
130
120
|
let {
|
|
131
121
|
garbageCollectAge,
|
|
@@ -134,22 +124,19 @@ function useAsyncData(path, loader, options = {}) {
|
|
|
134
124
|
} = options;
|
|
135
125
|
if (maxage === undefined) maxage = DEFAULT_MAXAGE;
|
|
136
126
|
if (refreshAge === undefined) refreshAge = maxage;
|
|
137
|
-
if (garbageCollectAge === undefined) garbageCollectAge = maxage;
|
|
138
|
-
// because that way we'll have issues with SSR (see details below).
|
|
127
|
+
if (garbageCollectAge === undefined) garbageCollectAge = maxage;
|
|
139
128
|
|
|
129
|
+
// Note: here we can't depend on useGlobalState() to init the initial value,
|
|
130
|
+
// because that way we'll have issues with SSR (see details below).
|
|
140
131
|
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
if (state === undefined) {
|
|
144
|
-
state = {
|
|
132
|
+
const state = globalState.get(path, {
|
|
133
|
+
initialValue: {
|
|
145
134
|
data: null,
|
|
146
135
|
numRefs: 0,
|
|
147
136
|
operationId: '',
|
|
148
137
|
timestamp: 0
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
}
|
|
152
|
-
|
|
138
|
+
}
|
|
139
|
+
});
|
|
153
140
|
if (globalState.ssrContext && !options.noSSR) {
|
|
154
141
|
if (!state.timestamp && !state.operationId) {
|
|
155
142
|
globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
|
|
@@ -171,7 +158,6 @@ function useAsyncData(path, loader, options = {}) {
|
|
|
171
158
|
globalState.set(numRefsPath, numRefs + 1);
|
|
172
159
|
return () => {
|
|
173
160
|
const state2 = globalState.get(path);
|
|
174
|
-
|
|
175
161
|
if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
|
|
176
162
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
177
163
|
/* eslint-disable no-console */
|
|
@@ -179,40 +165,43 @@ function useAsyncData(path, loader, options = {}) {
|
|
|
179
165
|
/* eslint-enable no-console */
|
|
180
166
|
}
|
|
181
167
|
|
|
182
|
-
globalState.set(path, {
|
|
168
|
+
globalState.set(path, {
|
|
169
|
+
...state2,
|
|
183
170
|
data: null,
|
|
184
171
|
numRefs: 0,
|
|
185
172
|
timestamp: 0
|
|
186
173
|
});
|
|
187
174
|
} else globalState.set(numRefsPath, state2.numRefs - 1);
|
|
188
175
|
};
|
|
189
|
-
}, [garbageCollectAge, globalState, path]);
|
|
176
|
+
}, [garbageCollectAge, globalState, path]);
|
|
177
|
+
|
|
178
|
+
// Note: a bunch of Rules of Hooks ignored belows because in our very
|
|
190
179
|
// special case the otherwise wrong behavior is actually what we need.
|
|
191
|
-
// Data loading and refreshing.
|
|
192
180
|
|
|
181
|
+
// Data loading and refreshing.
|
|
193
182
|
let loadTriggered = false;
|
|
194
183
|
(0, _react.useEffect)(() => {
|
|
195
184
|
// eslint-disable-line react-hooks/rules-of-hooks
|
|
196
185
|
const state2 = globalState.get(path);
|
|
197
|
-
|
|
198
186
|
if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt() === 'S')) {
|
|
199
187
|
load(path, loader, globalState, state2.data);
|
|
200
188
|
loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
|
|
201
189
|
}
|
|
202
190
|
});
|
|
191
|
+
|
|
203
192
|
const deps = options.deps || [];
|
|
204
193
|
(0, _react.useEffect)(() => {
|
|
205
194
|
// eslint-disable-line react-hooks/rules-of-hooks
|
|
206
195
|
if (!loadTriggered && deps.length) load(path, loader, globalState);
|
|
207
196
|
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
|
|
208
|
-
}
|
|
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
|
-
|
|
197
|
+
}
|
|
214
198
|
|
|
215
|
-
const [localState] = (0, _useGlobalState.default)(path
|
|
199
|
+
const [localState] = (0, _useGlobalState.default)(path, {
|
|
200
|
+
data: null,
|
|
201
|
+
numRefs: 0,
|
|
202
|
+
operationId: '',
|
|
203
|
+
timestamp: 0
|
|
204
|
+
});
|
|
216
205
|
return {
|
|
217
206
|
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
218
207
|
loading: Boolean(localState.operationId),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/useAsyncData.js"],"names":["DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationId","operationIdPath","set","data","get","state","groupCollapsed","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","numRefs","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","loading","Boolean"],"mappings":";;;;;;;;;AAIA;;AACA;;AACA;;AAEA;;AACA;;AACA;;AAVA;AACA;AACA;AAUA,MAAMA,cAAc,GAAG,IAAI,EAAJ,GAAS,IAAhC,C,CAAsC;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,eAAeC,IAAf,CAAoBC,IAApB,EAA0BC,MAA1B,EAAkCC,WAAlC,EAA+CC,OAA/C,EAAwDC,UA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CAAf;;AACA,UAAIyB,UAAU,GAAGP,IAAI,CAACC,GAAL,KAAac,MAAM,CAAChB,SAAjC,KACA,CAACgB,MAAM,CAACvB,WAAR,IAAuBuB,MAAM,CAACvB,WAAP,CAAmByB,MAAnB,OAAgC,GADvD,CAAJ,EACiE;AAC/DpC,QAAAA,IAAI,CAACC,IAAD,EAAOC,MAAP,EAAeC,WAAf,EAA4B+B,MAAM,CAACpB,IAAnC,CAAJ;AACAqB,QAAAA,aAAa,GAAG,IAAhB,CAF+D,CAEzC;AACvB;AACF,KAPD;AASA,UAAME,IAAI,GAAGd,OAAO,CAACc,IAAR,IAAgB,EAA7B;AACA,0BAAU,MAAM;AAAE;AAChB,UAAI,CAACF,aAAD,IAAkBE,IAAI,CAACC,MAA3B,EAAmCtC,IAAI,CAACC,IAAD,EAAOC,MAAP,EAAeC,WAAf,CAAJ;AACpC,KAFD,EAEGkC,IAFH,EAtDK,CAwDK;AACX,GAnFD,CAqFA;AACA;AACA;AACA;AACA;;;AACA,QAAM,CAACE,UAAD,IAAe,6BAAetC,IAAf,CAArB;AAEA,SAAO;AACLa,IAAAA,IAAI,EAAEW,MAAM,GAAGN,IAAI,CAACC,GAAL,KAAamB,UAAU,CAACrB,SAAjC,GAA6C,IAA7C,GAAoDqB,UAAU,CAACzB,IADhE;AAEL0B,IAAAA,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC5B,WAAZ,CAFX;AAGLO,IAAAA,SAAS,EAAEqB,UAAU,CAACrB;AAHjB,GAAP;AAKD","sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [oldData] Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param {object} [options] Additional options.\n * @param {any[]} [options.deps=[]] An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param {number} [options.refreshAge=maxage] The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) garbageCollectAge = maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n let state = globalState.get(path);\n if (state === undefined) {\n state = {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n globalState.set(path, state);\n }\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state2 = globalState.get(path);\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2 = globalState.get(path);\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt() === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n // Note: this subscription to updates of the global state segment must be\n // here, after the possible initialization of the loading operation, to take\n // into effect the resulting loading state. This mostly ensures the correct\n // SSR in the edge case when the loading starts, but times out, and incomplete\n // render has to be served.\n const [localState] = useGlobalState(path);\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n"],"file":"useAsyncData.js"}
|
|
1
|
+
{"version":3,"file":"useAsyncData.js","names":["DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","isDebugMode","console","log","operationId","uuid","operationIdPath","set","data","get","state","groupCollapsed","cloneDeep","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","getGlobalState","initialValue","numRefs","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.js"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [oldData] Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param {object} [options] Additional options.\n * @param {any[]} [options.deps=[]] An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param {number} [options.refreshAge=maxage] The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) garbageCollectAge = maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get(path, {\n initialValue: {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n },\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state2 = globalState.get(path);\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2 = globalState.get(path);\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt() === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState(path, {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n });\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n"],"mappings":";;;;;;;AAIA;AACA;AACA;AAEA;AACA;AACA;AAVA;AACA;AACA;;AAUA,MAAMA,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,IAA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M,EAAE,KAAK,GAAG,CAAC,EAAE;QAC/D1C,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAEqC,MAAM,CAACxB,IAAI,CAAC;QAC5CyB,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;;IAEF,MAAME,IAAI,GAAGjB,OAAO,CAACiB,IAAI,IAAI,EAAE;IAC/B,IAAAL,gBAAS,EAAC,MAAM;MAAE;MAChB,IAAI,CAACG,aAAa,IAAIE,IAAI,CAACC,MAAM,EAAE5C,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,CAAC;IACpE,CAAC,EAAEwC,IAAI,CAAC,CAAC,CAAC;EACZ;;EAEA,MAAM,CAACE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EAAC7C,IAAI,EAAE;IACxCe,IAAI,EAAE,IAAI;IACViB,OAAO,EAAE,CAAC;IACVrB,WAAW,EAAE,EAAE;IACfS,SAAS,EAAE;EACb,CAAC,CAAC;EAEF,OAAO;IACLL,IAAI,EAAEY,MAAM,GAAGN,IAAI,CAACC,GAAG,EAAE,GAAGsB,UAAU,CAACxB,SAAS,GAAG,IAAI,GAAGwB,UAAU,CAAC7B,IAAI;IACzE+B,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACjC,WAAW,CAAC;IACxCS,SAAS,EAAEwB,UAAU,CAACxB;EACxB,CAAC;AACH"}
|
|
@@ -4,15 +4,10 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
6
|
exports.default = useGlobalState;
|
|
7
|
-
|
|
8
7
|
var _lodash = require("lodash");
|
|
9
|
-
|
|
10
8
|
var _react = require("react");
|
|
11
|
-
|
|
12
9
|
var _GlobalStateProvider = require("./GlobalStateProvider");
|
|
13
|
-
|
|
14
10
|
var _utils = require("./utils");
|
|
15
|
-
|
|
16
11
|
// Hook for updates of global state.
|
|
17
12
|
|
|
18
13
|
/**
|
|
@@ -66,67 +61,54 @@ var _utils = require("./utils");
|
|
|
66
61
|
* stable function: it does not change between component re-renders.
|
|
67
62
|
*/
|
|
68
63
|
function useGlobalState(path, initialValue) {
|
|
69
|
-
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
70
|
-
let state = globalState.get(path);
|
|
71
|
-
|
|
72
|
-
if (state === undefined && initialValue !== undefined) {
|
|
73
|
-
const value = (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue;
|
|
74
|
-
state = globalState.set(path, value);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const [localState, setLocalState] = (0, _react.useState)(() => state);
|
|
78
|
-
(0, _react.useEffect)(() => {
|
|
79
|
-
// Note: the "callback.active" flag below is needed to workaround the issue
|
|
80
|
-
// https://github.com/birdofpreyru/react-global-state/issues/33,
|
|
81
|
-
// which, unfortunately, I am not able to reproduce in test environment,
|
|
82
|
-
// but I definitely seen it in the wild.
|
|
83
|
-
const callback = () => {
|
|
84
|
-
if (callback.active) {
|
|
85
|
-
const newState = globalState.get(path);
|
|
86
|
-
if (newState !== localState) setLocalState(() => newState);
|
|
87
|
-
}
|
|
88
|
-
};
|
|
89
|
-
|
|
90
|
-
callback.active = true;
|
|
91
|
-
globalState.watch(callback);
|
|
92
|
-
callback();
|
|
93
|
-
return () => {
|
|
94
|
-
delete callback.active;
|
|
95
|
-
globalState.unWatch(callback);
|
|
96
|
-
};
|
|
97
|
-
}, [globalState, localState, path]);
|
|
98
64
|
const ref = (0, _react.useRef)();
|
|
99
|
-
|
|
100
65
|
if (!ref.current) {
|
|
101
66
|
ref.current = {
|
|
102
|
-
|
|
103
|
-
path,
|
|
67
|
+
callbacks: [],
|
|
104
68
|
setter: value => {
|
|
105
|
-
const
|
|
106
|
-
|
|
69
|
+
const rc = ref.current;
|
|
70
|
+
const newState = (0, _lodash.isFunction)(value) ? value(rc.state) : value;
|
|
107
71
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
108
72
|
/* eslint-disable no-console */
|
|
109
|
-
console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${
|
|
110
|
-
console.log('New value:', (0, _lodash.cloneDeep)(
|
|
73
|
+
console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
|
|
74
|
+
console.log('New value:', (0, _lodash.cloneDeep)(newState));
|
|
111
75
|
console.groupEnd();
|
|
112
76
|
/* eslint-enable no-console */
|
|
113
77
|
}
|
|
114
78
|
|
|
115
|
-
globalState.set(
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
79
|
+
rc.globalState.set(rc.path, newState);
|
|
80
|
+
},
|
|
81
|
+
watcher: () => {
|
|
82
|
+
const rc = ref.current;
|
|
83
|
+
const state = rc.globalState.get(rc.path);
|
|
84
|
+
if (state !== rc.state) {
|
|
85
|
+
for (let i = 0; i < rc.callbacks.length; ++i) {
|
|
86
|
+
rc.callbacks[i]();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
123
89
|
}
|
|
124
90
|
};
|
|
125
|
-
} else {
|
|
126
|
-
ref.current.localState = localState;
|
|
127
|
-
ref.current.path = path;
|
|
128
91
|
}
|
|
129
|
-
|
|
130
|
-
|
|
92
|
+
const rc = ref.current;
|
|
93
|
+
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
94
|
+
rc.globalState = globalState;
|
|
95
|
+
rc.path = path;
|
|
96
|
+
rc.state = (0, _react.useSyncExternalStore)(cb => {
|
|
97
|
+
rc.callbacks.push(cb);
|
|
98
|
+
}, () => rc.globalState.get(rc.path, {
|
|
99
|
+
initialValue
|
|
100
|
+
}), () => rc.globalState.get(rc.path, {
|
|
101
|
+
initialValue,
|
|
102
|
+
initialState: true
|
|
103
|
+
}));
|
|
104
|
+
(0, _react.useEffect)(() => {
|
|
105
|
+
globalState.watch(rc.watcher);
|
|
106
|
+
rc.watcher();
|
|
107
|
+
return () => globalState.unWatch(rc.watcher);
|
|
108
|
+
}, [globalState, rc]);
|
|
109
|
+
(0, _react.useEffect)(() => {
|
|
110
|
+
rc.watcher();
|
|
111
|
+
}, [path, rc]);
|
|
112
|
+
return [rc.state, rc.setter];
|
|
131
113
|
}
|
|
132
114
|
//# sourceMappingURL=useGlobalState.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["useGlobalState","path","initialValue","ref","useRef","current","callbacks","setter","value","rc","newState","isFunction","state","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeep","groupEnd","globalState","set","watcher","get","i","length","getGlobalState","useSyncExternalStore","cb","push","initialState","useEffect","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":";;;;;;AAEA;AACA;AAEA;AACA;AANA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASA,cAAc,CAACC,IAAI,EAAEC,YAAY,EAAE;EACzD,MAAMC,GAAG,GAAG,IAAAC,aAAM,GAAE;EACpB,IAAI,CAACD,GAAG,CAACE,OAAO,EAAE;IAChBF,GAAG,CAACE,OAAO,GAAG;MACZC,SAAS,EAAE,EAAE;MACbC,MAAM,EAAGC,KAAK,IAAK;QACjB,MAAMC,EAAE,GAAGN,GAAG,CAACE,OAAO;QACtB,MAAMK,QAAQ,GAAG,IAAAC,kBAAU,EAACH,KAAK,CAAC,GAAGA,KAAK,CAACC,EAAE,CAACG,KAAK,CAAC,GAAGJ,KAAK;QAC5D,IAAIK,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,GAAE,EAAE;UAC1D;UACAC,OAAO,CAACC,cAAc,CACnB,+DACCT,EAAE,CAACR,IAAI,IAAI,EACZ,EAAC,CACH;UACDgB,OAAO,CAACE,GAAG,CAAC,YAAY,EAAE,IAAAC,iBAAS,EAACV,QAAQ,CAAC,CAAC;UAC9CO,OAAO,CAACI,QAAQ,EAAE;UAClB;QACF;;QACAZ,EAAE,CAACa,WAAW,CAACC,GAAG,CAACd,EAAE,CAACR,IAAI,EAAES,QAAQ,CAAC;MACvC,CAAC;MACDc,OAAO,EAAE,MAAM;QACb,MAAMf,EAAE,GAAGN,GAAG,CAACE,OAAO;QACtB,MAAMO,KAAK,GAAGH,EAAE,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ACA,EAAE,CAACG,KAAK,EAAEH,EAAE,CAACF,MAAM,CAAC;AAC9B"}
|
package/build/node/utils.js
CHANGED
|
@@ -5,7 +5,6 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
});
|
|
6
6
|
exports.default = void 0;
|
|
7
7
|
exports.isDebugMode = isDebugMode;
|
|
8
|
-
|
|
9
8
|
// Auxiliary stuff.
|
|
10
9
|
|
|
11
10
|
/**
|
|
@@ -27,7 +26,6 @@ function isDebugMode() {
|
|
|
27
26
|
return false;
|
|
28
27
|
}
|
|
29
28
|
}
|
|
30
|
-
|
|
31
29
|
var _default = null;
|
|
32
30
|
exports.default = _default;
|
|
33
31
|
//# sourceMappingURL=utils.js.map
|
package/build/node/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
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;AACO,SAASA,WAAW,GAAG;EAC5B,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,OAAO,KAAK;EACd;AACF;AAAC,eAEc,IAAI;AAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dr.pogodin/react-global-state",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "Hook-based global state for React",
|
|
5
5
|
"main": "./build/node/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -35,37 +35,37 @@
|
|
|
35
35
|
},
|
|
36
36
|
"homepage": "https://dr.pogodin.studio/docs/react-global-state/index.html",
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@babel/runtime": "^7.
|
|
38
|
+
"@babel/runtime": "^7.19.4",
|
|
39
39
|
"lodash": "^4.17.21",
|
|
40
|
-
"uuid": "^
|
|
40
|
+
"uuid": "^9.0.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@babel/cli": "^7.
|
|
44
|
-
"@babel/core": "^7.
|
|
45
|
-
"@babel/eslint-parser": "^7.
|
|
46
|
-
"@babel/eslint-plugin": "^7.
|
|
47
|
-
"@babel/node": "^7.
|
|
48
|
-
"@babel/plugin-transform-runtime": "^7.
|
|
49
|
-
"@babel/preset-env": "^7.
|
|
50
|
-
"@babel/preset-react": "^7.
|
|
51
|
-
"babel-jest": "^
|
|
43
|
+
"@babel/cli": "^7.19.3",
|
|
44
|
+
"@babel/core": "^7.19.6",
|
|
45
|
+
"@babel/eslint-parser": "^7.19.1",
|
|
46
|
+
"@babel/eslint-plugin": "^7.19.1",
|
|
47
|
+
"@babel/node": "^7.19.1",
|
|
48
|
+
"@babel/plugin-transform-runtime": "^7.19.6",
|
|
49
|
+
"@babel/preset-env": "^7.19.4",
|
|
50
|
+
"@babel/preset-react": "^7.18.6",
|
|
51
|
+
"babel-jest": "^29.2.1",
|
|
52
52
|
"babel-plugin-module-resolver": "^4.1.0",
|
|
53
|
-
"eslint": "^8.
|
|
53
|
+
"eslint": "^8.25.0",
|
|
54
54
|
"eslint-config-airbnb": "^19.0.4",
|
|
55
55
|
"eslint-import-resolver-babel-module": "^5.3.1",
|
|
56
56
|
"eslint-plugin-import": "^2.26.0",
|
|
57
|
-
"eslint-plugin-jest": "^
|
|
58
|
-
"eslint-plugin-jsx-a11y": "^6.
|
|
59
|
-
"eslint-plugin-react": "^7.
|
|
60
|
-
"eslint-plugin-react-hooks": "^4.
|
|
61
|
-
"jest": "^
|
|
62
|
-
"jest-environment-jsdom": "^
|
|
57
|
+
"eslint-plugin-jest": "^27.1.3",
|
|
58
|
+
"eslint-plugin-jsx-a11y": "^6.6.1",
|
|
59
|
+
"eslint-plugin-react": "^7.31.10",
|
|
60
|
+
"eslint-plugin-react-hooks": "^4.6.0",
|
|
61
|
+
"jest": "^29.2.1",
|
|
62
|
+
"jest-environment-jsdom": "^29.2.1",
|
|
63
63
|
"mockdate": "^3.0.5",
|
|
64
64
|
"pretty": "^2.0.0",
|
|
65
65
|
"rimraf": "^3.0.2"
|
|
66
66
|
},
|
|
67
67
|
"peerDependencies": {
|
|
68
|
-
"react": "^18.
|
|
69
|
-
"react-dom": "^18.
|
|
68
|
+
"react": "^18.2.0",
|
|
69
|
+
"react-dom": "^18.2.0"
|
|
70
70
|
}
|
|
71
71
|
}
|