@dr.pogodin/react-global-state 0.9.3 → 0.10.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +3 -328
  2. package/build/GlobalState.d.ts +75 -0
  3. package/build/GlobalState.js +193 -0
  4. package/build/GlobalStateProvider.d.ts +55 -0
  5. package/build/GlobalStateProvider.js +103 -0
  6. package/build/SsrContext.d.ts +6 -0
  7. package/build/SsrContext.js +10 -0
  8. package/build/index.d.ts +8 -0
  9. package/build/index.js +23 -0
  10. package/build/{module/useAsyncCollection.js → useAsyncCollection.d.ts} +16 -23
  11. package/build/useAsyncCollection.js +14 -0
  12. package/build/useAsyncData.d.ts +76 -0
  13. package/build/useAsyncData.js +150 -0
  14. package/build/{module/useGlobalState.js → useGlobalState.d.ts} +11 -62
  15. package/build/useGlobalState.js +49 -0
  16. package/build/utils.d.ts +31 -0
  17. package/build/{node/utils.js → utils.js} +11 -17
  18. package/build/withGlobalStateType.d.ts +39 -0
  19. package/build/withGlobalStateType.js +55 -0
  20. package/package.json +48 -27
  21. package/src/GlobalState.ts +279 -0
  22. package/src/GlobalStateProvider.tsx +116 -0
  23. package/src/SsrContext.ts +11 -0
  24. package/src/index.ts +33 -0
  25. package/{build/node/useAsyncCollection.js → src/useAsyncCollection.ts} +58 -25
  26. package/src/useAsyncData.ts +287 -0
  27. package/src/useGlobalState.ts +158 -0
  28. package/src/utils.ts +59 -0
  29. package/src/withGlobalStateType.ts +118 -0
  30. package/tsconfig.json +9 -0
  31. package/build/module/GlobalState.js +0 -191
  32. package/build/module/GlobalState.js.map +0 -1
  33. package/build/module/GlobalStateProvider.js +0 -81
  34. package/build/module/GlobalStateProvider.js.map +0 -1
  35. package/build/module/index.js +0 -12
  36. package/build/module/index.js.map +0 -1
  37. package/build/module/useAsyncCollection.js.map +0 -1
  38. package/build/module/useAsyncData.js +0 -206
  39. package/build/module/useAsyncData.js.map +0 -1
  40. package/build/module/useGlobalState.js.map +0 -1
  41. package/build/module/utils.js +0 -23
  42. package/build/module/utils.js.map +0 -1
  43. package/build/node/GlobalState.js +0 -174
  44. package/build/node/GlobalState.js.map +0 -1
  45. package/build/node/GlobalStateProvider.js +0 -88
  46. package/build/node/GlobalStateProvider.js.map +0 -1
  47. package/build/node/index.js +0 -56
  48. package/build/node/index.js.map +0 -1
  49. package/build/node/useAsyncCollection.js.map +0 -1
  50. package/build/node/useAsyncData.js +0 -211
  51. package/build/node/useAsyncData.js.map +0 -1
  52. package/build/node/useGlobalState.js +0 -114
  53. package/build/node/useGlobalState.js.map +0 -1
  54. package/build/node/utils.js.map +0 -1
  55. package/index.d.ts +0 -70
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["_GlobalStateProvider","_interopRequireWildcard","require","_useAsyncCollection","_interopRequireDefault","_useAsyncData","_useGlobalState","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","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,IAAAA,oBAAA,GAAAC,uBAAA,CAAAC,OAAA;AAMA,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D;AACA;AACA;AACA;AACA,IAAI,CAACW,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 +0,0 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["_useAsyncData","_interopRequireDefault","require","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,IAAAA,aAAA,GAAAC,sBAAA,CAAAC,OAAA;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,SAASC,kBAAkBA,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"}
@@ -1,211 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = useAsyncData;
8
- var _lodash = require("lodash");
9
- var _react = require("react");
10
- var _uuid = require("uuid");
11
- var _GlobalStateProvider = require("./GlobalStateProvider");
12
- var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
13
- var _utils = require("./utils");
14
- /**
15
- * Loads and uses async data into the GlobalState path.
16
- */
17
-
18
- const DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.
19
-
20
- /**
21
- * Executes the data loading operation.
22
- * @param {string} path Data segment path inside the global state.
23
- * @param {function} loader Data loader.
24
- * @param {GlobalState} globalState The global state instance.
25
- * @param {any} [oldData] Optional. Previously fetched data, currently stored in
26
- * the state, if already fetched by the caller; otherwise, they will be fetched
27
- * by the load() function itself.
28
- * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be
29
- * 'C' at the client-side (default), or 'S' at the server-side (within SSR
30
- * context).
31
- * @return {Promise} Resolves once the operation is done.
32
- * @ignore
33
- */
34
- async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
35
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
36
- /* eslint-disable no-console */
37
- console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
38
- /* eslint-enable no-console */
39
- }
40
-
41
- const operationId = opIdPrefix + (0, _uuid.v4)();
42
- const operationIdPath = path ? `${path}.operationId` : 'operationId';
43
- globalState.set(operationIdPath, operationId);
44
- const data = await loader(oldData || globalState.get(path).data);
45
- const state = globalState.get(path);
46
- if (operationId === state.operationId) {
47
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
48
- /* eslint-disable no-console */
49
- console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
50
- console.log('Data:', (0, _lodash.cloneDeep)(data));
51
- /* eslint-enable no-console */
52
- }
53
-
54
- globalState.set(path, {
55
- ...state,
56
- data,
57
- operationId: '',
58
- timestamp: Date.now()
59
- });
60
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
61
- /* eslint-disable no-console */
62
- console.groupEnd();
63
- /* eslint-enable no-console */
64
- }
65
- }
66
- }
67
-
68
- /**
69
- * Resolves asynchronous data, and stores them at given `path` of global
70
- * state. When multiple components rely on asynchronous data at the same `path`,
71
- * the data are resolved once, and reused until their age is within specified
72
- * bounds. Once the data are stale, the hook allows to refresh them. It also
73
- * garbage-collects stale data from the global state when the last component
74
- * relying on them is unmounted.
75
- * @param {string} path Dot-delimitered state path, where data envelop is
76
- * stored.
77
- * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)
78
- * data, which should be stored at the global state `path`. When multiple
79
- * components
80
- * use `useAsyncData()` hook for the same `path`, the library assumes that all
81
- * hook instances are called with the same `loader` (_i.e._ whichever of these
82
- * loaders is used to resolve async data, the result is acceptable to be reused
83
- * in all related components).
84
- * @param {object} [options] Additional options.
85
- * @param {any[]} [options.deps=[]] An array of dependencies, which trigger
86
- * data reload when changed. Given dependency changes are watched shallowly
87
- * (similarly to the standard React's
88
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
89
- * @param {boolean} [options.noSSR] If `true`, this hook won't load data during
90
- * server-side rendering.
91
- * @param {number} [options.garbageCollectAge=maxage] The maximum age of data
92
- * (in milliseconds), after which they are dropped from the state when the last
93
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
94
- * `maxage` option value.
95
- * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of
96
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
97
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
98
- * @param {number} [options.refreshAge=maxage] The maximum age of data
99
- * (in milliseconds), after which their refreshment will be triggered when
100
- * any component referencing them via `useAsyncData()` hook (re-)renders.
101
- * Defaults to `maxage` value.
102
- * @return {{
103
- * data: any,
104
- * loading: boolean,
105
- * timestamp: number
106
- * }} Returns an object with three fields: `data` holds the actual result of
107
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
108
- * is a boolean flag, which is `true` if data are being loaded (the hook is
109
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
110
- * is Unix timestamp of related data currently loaded into the global state.
111
- *
112
- * Note that loaded data, if any, are stored at the given `path` of global state
113
- * along with related meta-information, using slightly different state segment
114
- * structure (see {@link AsyncDataEnvelope}). That segment of the global state
115
- * can be accessed, and even modified using other hooks,
116
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
117
- * `useAsyncData()` hooks logic.
118
- */
119
- function useAsyncData(path, loader, options = {}) {
120
- let {
121
- garbageCollectAge,
122
- maxage,
123
- refreshAge
124
- } = options;
125
- if (maxage === undefined) maxage = DEFAULT_MAXAGE;
126
- if (refreshAge === undefined) refreshAge = maxage;
127
- if (garbageCollectAge === undefined) garbageCollectAge = maxage;
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).
131
- const globalState = (0, _GlobalStateProvider.getGlobalState)();
132
- const state = globalState.get(path, {
133
- initialValue: {
134
- data: null,
135
- numRefs: 0,
136
- operationId: '',
137
- timestamp: 0
138
- }
139
- });
140
- if (globalState.ssrContext && !options.noSSR) {
141
- if (!state.timestamp && !state.operationId) {
142
- globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
143
- }
144
- } else {
145
- // This takes care about the client-side reference counting, and garbage
146
- // collection.
147
- //
148
- // Note: the Rules of Hook below are violated by conditional call to a hook,
149
- // but as the condition is actually server-side or client-side environment,
150
- // it is effectively non-conditional at the runtime.
151
- //
152
- // TODO: Though, maybe there is a way to refactor it into a cleaner code.
153
- // The same applies to other useEffect() hooks below.
154
- (0, _react.useEffect)(() => {
155
- // eslint-disable-line react-hooks/rules-of-hooks
156
- const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
157
- const numRefs = globalState.get(numRefsPath);
158
- globalState.set(numRefsPath, numRefs + 1);
159
- return () => {
160
- const state2 = globalState.get(path);
161
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
162
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
163
- /* eslint-disable no-console */
164
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
165
- /* eslint-enable no-console */
166
- }
167
-
168
- globalState.set(path, {
169
- ...state2,
170
- data: null,
171
- numRefs: 0,
172
- timestamp: 0
173
- });
174
- } else globalState.set(numRefsPath, state2.numRefs - 1);
175
- };
176
- }, [garbageCollectAge, globalState, path]);
177
-
178
- // Note: a bunch of Rules of Hooks ignored belows because in our very
179
- // special case the otherwise wrong behavior is actually what we need.
180
-
181
- // Data loading and refreshing.
182
- let loadTriggered = false;
183
- (0, _react.useEffect)(() => {
184
- // eslint-disable-line react-hooks/rules-of-hooks
185
- const state2 = globalState.get(path);
186
- if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt() === 'S')) {
187
- load(path, loader, globalState, state2.data);
188
- loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
189
- }
190
- });
191
-
192
- const deps = options.deps || [];
193
- (0, _react.useEffect)(() => {
194
- // eslint-disable-line react-hooks/rules-of-hooks
195
- if (!loadTriggered && deps.length) load(path, loader, globalState);
196
- }, deps); // eslint-disable-line react-hooks/exhaustive-deps
197
- }
198
-
199
- const [localState] = (0, _useGlobalState.default)(path, {
200
- data: null,
201
- numRefs: 0,
202
- operationId: '',
203
- timestamp: 0
204
- });
205
- return {
206
- data: maxage < Date.now() - localState.timestamp ? null : localState.data,
207
- loading: Boolean(localState.operationId),
208
- timestamp: localState.timestamp
209
- };
210
- }
211
- //# sourceMappingURL=useAsyncData.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAsyncData.js","names":["_lodash","require","_react","_uuid","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","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,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AACA,IAAAM,MAAA,GAAAN,OAAA;AAVA;AACA;AACA;;AAUA,MAAMO,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,IAAIA,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,UAAU,GAAG,GAAG,EAAE;EACxE,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,GAAE,EAAE;IAC1D;IACAC,OAAO,CA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,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"}
@@ -1,114 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = useGlobalState;
7
- var _lodash = require("lodash");
8
- var _react = require("react");
9
- var _GlobalStateProvider = require("./GlobalStateProvider");
10
- var _utils = require("./utils");
11
- // Hook for updates of global state.
12
-
13
- /**
14
- * The primary hook for interacting with the global state, modeled after
15
- * the standard React's
16
- * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
17
- * It subscribes a component to a given `path` of global state, and provides
18
- * a function to update it. Each time the value at `path` changes, the hook
19
- * triggers re-render of its host component.
20
- *
21
- * **Note:**
22
- * - For performance, the library does not copy objects written to / read from
23
- * global state paths. You MUST NOT manually mutate returned state values,
24
- * or change objects already written into the global state, without explicitly
25
- * clonning them first yourself.
26
- * - State update notifications are asynchronous. When your code does multiple
27
- * global state updates in the same React rendering cycle, all state update
28
- * notifications are queued and dispatched together, after the current
29
- * rendering cycle. In other words, in any given rendering cycle the global
30
- * state values are "fixed", and all changes becomes visible at once in the
31
- * next triggered rendering pass.
32
- *
33
- * @param {string} [path] Dot-delimitered state path. It can be undefined to
34
- * subscribe for entire state.
35
- *
36
- * Under-the-hood state values are read and written using `lodash`
37
- * [_.get()](https://lodash.com/docs/4.17.15#get) and
38
- * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
39
- * to access state paths which have not been created before.
40
- * @param {any} [initialValue] Initial value to set at the `path`, or its
41
- * factory:
42
- * - If a function is given, it will act similar to
43
- * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
44
- * only if the value at `path` is `undefined`, the function will be executed,
45
- * and the value it returns will be written to the `path`.
46
- * - Otherwise, the given value itself will be written to the `path`,
47
- * if the current value at `path` is `undefined`.
48
- * @return {Array} It returs an array with two elements: `[value, setValue]`:
49
- *
50
- * - The `value` is the current value at given `path`.
51
- *
52
- * - The `setValue()` is setter function to write a new value to the `path`.
53
- *
54
- * Similar to the standard React's `useState()`, it supports
55
- * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
56
- * if `setValue()` is called with a function as argument, that function will
57
- * be called and its return value will be written to `path`. Otherwise,
58
- * the argument of `setValue()` itself is written to `path`.
59
- *
60
- * Also, similar to the standard React's state setters, `setValue()` is
61
- * stable function: it does not change between component re-renders.
62
- */
63
- function useGlobalState(path, initialValue) {
64
- const ref = (0, _react.useRef)();
65
- if (!ref.current) {
66
- ref.current = {
67
- callbacks: [],
68
- setter: value => {
69
- const rc = ref.current;
70
- const newState = (0, _lodash.isFunction)(value) ? value(rc.state) : value;
71
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
72
- /* eslint-disable no-console */
73
- console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
74
- console.log('New value:', (0, _lodash.cloneDeep)(newState));
75
- console.groupEnd();
76
- /* eslint-enable no-console */
77
- }
78
-
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
- }
89
- }
90
- };
91
- }
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];
113
- }
114
- //# sourceMappingURL=useGlobalState.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_GlobalStateProvider","_utils","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,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAEA,IAAAE,oBAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAH,OAAA;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,SAASI,cAAcA,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,EAAC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AAG,CAAChB,EAAE,CAACR,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EACnD,MAAMO,EAAE,CAACa,WAAW,CAACG,GAAG,CAAChB,EAAE,CAACR,IAAI,EAAE;IAAEC,YAAY;IAAE8B,YAAY,EAAE;EAAK,CAAC,CAAC,CACxE;EAED,IAAAC,gBAAS,EAAC,MAAM;IACdX,WAAW,CAACY,KAAK,CAACzB,EAAE,CAACe,OAAO,CAAC;IAC7Bf,EAAE,CAACe,OAAO,EAAE;IACZ,OAAO,MAAMF,WAAW,CAACa,OAAO,CAAC1B,EAAE,CAACe,OAAO,CAAC;EAC9C,CAAC,EAAE,CAACF,WAAW,EAAEb,EAAE,CAAC,CAAC;EAErB,IAAAwB,gBAAS,EAAC,MAAM;IACdxB,EAAE,CAACe,OAAO,EAAE;EACd,CAAC,EAAE,CAACvB,IAAI,EAAEQ,EAAE,CAAC,CAAC;EAEd,OAAO,CAACA,EAAE,CAACG,KAAK,EAAEH,EAAE,CAACF,MAAM,CAAC;AAC9B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error","_default","exports","default"],"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,WAAWA,CAAA,EAAG;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,IAAAC,QAAA,GAEc,IAAI;AAAAC,OAAA,CAAAC,OAAA,GAAAF,QAAA"}
package/index.d.ts DELETED
@@ -1,70 +0,0 @@
1
- import React from "react";
2
-
3
- interface IAsyncDataEnvelope<DataT> {
4
- data: null|DataT,
5
- loading: boolean,
6
- timestamp: number,
7
- }
8
-
9
- interface ISsrContext<StateT> {
10
- dirty: boolean;
11
- pending: Array<Promise<any>>;
12
- state: StateT;
13
- }
14
-
15
- interface IGlobalState<StateT> {
16
- constructor: new (
17
- initialState: StateT,
18
- ssrContext: ISsrContext<StateT>,
19
- ) => IGlobalState<StateT>;
20
-
21
- get<T>(path?: string): T;
22
- set<T>(path: string|undefined, value: T): T;
23
- unWatch(callback: () => void);
24
- watch(callback: () => void);
25
- }
26
-
27
- type GlobalStateProviderProps<StateT> = {
28
- children?: React.ReactNode;
29
- initialState?: StateT;
30
- ssrContext?: ISsrContext<StateT>;
31
- stateProxy?: true|IGlobalState<StateT>;
32
- };
33
-
34
- export function GlobalStateProvider<StateT>(
35
- props: GlobalStateProviderProps<StateT>
36
- ): JSX.Element;
37
-
38
- export function getSsrContext<StateT>(throwWithoutSsrContext: boolean):
39
- ISsrContext<StateT>|undefined;
40
-
41
- export function getGlobalState<StateT>(): IGlobalState<StateT>;
42
-
43
- export function useGlobalState<T>(
44
- path: string|undefined,
45
- initialValue: T | (() => T),
46
- ): [
47
- value: T,
48
- setValue: (value: T | ((value: T) => T)) => void,
49
- ];
50
-
51
- type UseAsyncOptionsType = {
52
- deps?: Array<any>,
53
- noSSR?: boolean,
54
- garbageCollectAge?: number,
55
- maxage?: number,
56
- refreshAge?: number,
57
- };
58
-
59
- export function useAsyncData<DataT>(
60
- path: string|undefined,
61
- loader: (prevData: DataT|null) => DataT | Promise<DataT>,
62
- options?: UseAsyncOptionsType,
63
- ): IAsyncDataEnvelope<DataT>
64
-
65
- export function useAsyncCollection<DataT>(
66
- id: string,
67
- path: string|undefined,
68
- loader: (id: string, prevData: DataT|null) => DataT | Promise<DataT>,
69
- options?: UseAsyncOptionsType,
70
- ): IAsyncDataEnvelope<DataT>