@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.
- package/README.md +3 -328
- package/build/GlobalState.d.ts +75 -0
- package/build/GlobalState.js +193 -0
- package/build/GlobalStateProvider.d.ts +55 -0
- package/build/GlobalStateProvider.js +103 -0
- package/build/SsrContext.d.ts +6 -0
- package/build/SsrContext.js +10 -0
- package/build/index.d.ts +8 -0
- package/build/index.js +23 -0
- package/build/{module/useAsyncCollection.js → useAsyncCollection.d.ts} +16 -23
- package/build/useAsyncCollection.js +14 -0
- package/build/useAsyncData.d.ts +76 -0
- package/build/useAsyncData.js +150 -0
- package/build/{module/useGlobalState.js → useGlobalState.d.ts} +11 -62
- package/build/useGlobalState.js +49 -0
- package/build/utils.d.ts +31 -0
- package/build/{node/utils.js → utils.js} +11 -17
- package/build/withGlobalStateType.d.ts +39 -0
- package/build/withGlobalStateType.js +55 -0
- package/package.json +48 -27
- package/src/GlobalState.ts +279 -0
- package/src/GlobalStateProvider.tsx +116 -0
- package/src/SsrContext.ts +11 -0
- package/src/index.ts +33 -0
- package/{build/node/useAsyncCollection.js → src/useAsyncCollection.ts} +58 -25
- package/src/useAsyncData.ts +287 -0
- package/src/useGlobalState.ts +158 -0
- package/src/utils.ts +59 -0
- package/src/withGlobalStateType.ts +118 -0
- package/tsconfig.json +9 -0
- package/build/module/GlobalState.js +0 -191
- package/build/module/GlobalState.js.map +0 -1
- package/build/module/GlobalStateProvider.js +0 -81
- package/build/module/GlobalStateProvider.js.map +0 -1
- package/build/module/index.js +0 -12
- package/build/module/index.js.map +0 -1
- package/build/module/useAsyncCollection.js.map +0 -1
- package/build/module/useAsyncData.js +0 -206
- package/build/module/useAsyncData.js.map +0 -1
- package/build/module/useGlobalState.js.map +0 -1
- package/build/module/utils.js +0 -23
- package/build/module/utils.js.map +0 -1
- package/build/node/GlobalState.js +0 -174
- package/build/node/GlobalState.js.map +0 -1
- package/build/node/GlobalStateProvider.js +0 -88
- package/build/node/GlobalStateProvider.js.map +0 -1
- package/build/node/index.js +0 -56
- package/build/node/index.js.map +0 -1
- package/build/node/useAsyncCollection.js.map +0 -1
- package/build/node/useAsyncData.js +0 -211
- package/build/node/useAsyncData.js.map +0 -1
- package/build/node/useGlobalState.js +0 -114
- package/build/node/useGlobalState.js.map +0 -1
- package/build/node/utils.js.map +0 -1
- package/index.d.ts +0 -70
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
|
3
|
+
var t = {};
|
|
4
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
5
|
+
t[p] = s[p];
|
|
6
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
7
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
8
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
9
|
+
t[p[i]] = s[p[i]];
|
|
10
|
+
}
|
|
11
|
+
return t;
|
|
12
|
+
};
|
|
13
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.getSsrContext = exports.getGlobalState = void 0;
|
|
18
|
+
const jsx_runtime_1 = require("react/jsx-runtime");
|
|
19
|
+
/* eslint-disable react/prop-types */
|
|
20
|
+
const lodash_1 = require("lodash");
|
|
21
|
+
const react_1 = require("react");
|
|
22
|
+
const GlobalState_1 = __importDefault(require("./GlobalState"));
|
|
23
|
+
const context = (0, react_1.createContext)(null);
|
|
24
|
+
/**
|
|
25
|
+
* Gets {@link GlobalState} instance from the context. In most cases
|
|
26
|
+
* you should use {@link useGlobalState}, and other hooks to interact with
|
|
27
|
+
* the global state, instead of accessing it directly.
|
|
28
|
+
* @return
|
|
29
|
+
*/
|
|
30
|
+
function getGlobalState() {
|
|
31
|
+
// Here Rules of Hooks are violated because "getGlobalState()" does not follow
|
|
32
|
+
// convention that hook names should start with use... This is intentional in
|
|
33
|
+
// our case, as getGlobalState() hook is intended for advance scenarious,
|
|
34
|
+
// while the normal interaction with the global state should happen via
|
|
35
|
+
// another hook, useGlobalState().
|
|
36
|
+
/* eslint-disable react-hooks/rules-of-hooks */
|
|
37
|
+
const globalState = (0, react_1.useContext)(context);
|
|
38
|
+
/* eslint-enable react-hooks/rules-of-hooks */
|
|
39
|
+
if (!globalState)
|
|
40
|
+
throw new Error('Missing GlobalStateProvider');
|
|
41
|
+
return globalState;
|
|
42
|
+
}
|
|
43
|
+
exports.getGlobalState = getGlobalState;
|
|
44
|
+
/**
|
|
45
|
+
* @category Hooks
|
|
46
|
+
* @desc Gets SSR context.
|
|
47
|
+
* @param throwWithoutSsrContext If `true` (default),
|
|
48
|
+
* this hook will throw if no SSR context is attached to the global state;
|
|
49
|
+
* set `false` to not throw in such case. In either case the hook will throw
|
|
50
|
+
* if the {@link <GlobalStateProvider>} (hence the state) is missing.
|
|
51
|
+
* @returns SSR context.
|
|
52
|
+
* @throws
|
|
53
|
+
* - If current component has no parent {@link <GlobalStateProvider>}
|
|
54
|
+
* in the rendered React tree.
|
|
55
|
+
* - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
|
|
56
|
+
* to the global state provided by {@link <GlobalStateProvider>}.
|
|
57
|
+
*/
|
|
58
|
+
function getSsrContext(throwWithoutSsrContext = true) {
|
|
59
|
+
const { ssrContext } = getGlobalState();
|
|
60
|
+
if (!ssrContext && throwWithoutSsrContext) {
|
|
61
|
+
throw new Error('No SSR context found');
|
|
62
|
+
}
|
|
63
|
+
return ssrContext;
|
|
64
|
+
}
|
|
65
|
+
exports.getSsrContext = getSsrContext;
|
|
66
|
+
/**
|
|
67
|
+
* Provides global state to its children.
|
|
68
|
+
* @param prop.children Component children, which will be provided with
|
|
69
|
+
* the global state, and rendered in place of the provider.
|
|
70
|
+
* @param prop.initialState Initial content of the global state.
|
|
71
|
+
* @param prop.ssrContext Server-side rendering (SSR) context.
|
|
72
|
+
* @param prop.stateProxy This option is useful for code
|
|
73
|
+
* splitting and SSR implementation:
|
|
74
|
+
* - If `true`, this provider instance will fetch and reuse the global state
|
|
75
|
+
* from a parent provider.
|
|
76
|
+
* - If `GlobalState` instance, it will be used by this provider.
|
|
77
|
+
* - If not given, a new `GlobalState` instance will be created and used.
|
|
78
|
+
*/
|
|
79
|
+
function GlobalStateProvider(_a) {
|
|
80
|
+
var { children } = _a, rest = __rest(_a, ["children"]);
|
|
81
|
+
const state = (0, react_1.useRef)();
|
|
82
|
+
if (!state.current) {
|
|
83
|
+
// NOTE: The last part of condition, "&& rest.stateProxy", is needed for
|
|
84
|
+
// graceful compatibility with JavaScript - if "undefined" stateProxy value
|
|
85
|
+
// is given, we want to follow the second branch, which creates a new
|
|
86
|
+
// GlobalState with whatever intiialState given.
|
|
87
|
+
if ('stateProxy' in rest && rest.stateProxy) {
|
|
88
|
+
if (rest.stateProxy === true)
|
|
89
|
+
state.current = getGlobalState();
|
|
90
|
+
else
|
|
91
|
+
state.current = rest.stateProxy;
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
const { initialState, ssrContext } = rest;
|
|
95
|
+
state.current = new GlobalState_1.default((0, lodash_1.isFunction)(initialState) ? initialState() : initialState, ssrContext);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return ((0, jsx_runtime_1.jsx)(context.Provider, { value: state.current, children: children }));
|
|
99
|
+
}
|
|
100
|
+
exports.default = GlobalStateProvider;
|
|
101
|
+
GlobalStateProvider.defaultProps = {
|
|
102
|
+
children: undefined,
|
|
103
|
+
};
|
package/build/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { default as GlobalState } from './GlobalState';
|
|
2
|
+
export { default as GlobalStateProvider, getGlobalState, getSsrContext, } from './GlobalStateProvider';
|
|
3
|
+
export { default as SsrContext } from './SsrContext';
|
|
4
|
+
export { type AsyncCollectionLoaderT, default as useAsyncCollection, } from './useAsyncCollection';
|
|
5
|
+
export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type UseAsyncDataOptionsT, type UseAsyncDataResT, default as useAsyncData, newAsyncDataEnvelope, } from './useAsyncData';
|
|
6
|
+
export { type SetterT, type UseGlobalStateResT, default as useGlobalState, } from './useGlobalState';
|
|
7
|
+
export { type ValueOrInitializerT } from './utils';
|
|
8
|
+
export { default as withGlobalStateType } from './withGlobalStateType';
|
package/build/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.withGlobalStateType = exports.useGlobalState = exports.newAsyncDataEnvelope = exports.useAsyncData = exports.useAsyncCollection = exports.SsrContext = exports.getSsrContext = exports.getGlobalState = exports.GlobalStateProvider = exports.GlobalState = void 0;
|
|
7
|
+
var GlobalState_1 = require("./GlobalState");
|
|
8
|
+
Object.defineProperty(exports, "GlobalState", { enumerable: true, get: function () { return __importDefault(GlobalState_1).default; } });
|
|
9
|
+
var GlobalStateProvider_1 = require("./GlobalStateProvider");
|
|
10
|
+
Object.defineProperty(exports, "GlobalStateProvider", { enumerable: true, get: function () { return __importDefault(GlobalStateProvider_1).default; } });
|
|
11
|
+
Object.defineProperty(exports, "getGlobalState", { enumerable: true, get: function () { return GlobalStateProvider_1.getGlobalState; } });
|
|
12
|
+
Object.defineProperty(exports, "getSsrContext", { enumerable: true, get: function () { return GlobalStateProvider_1.getSsrContext; } });
|
|
13
|
+
var SsrContext_1 = require("./SsrContext");
|
|
14
|
+
Object.defineProperty(exports, "SsrContext", { enumerable: true, get: function () { return __importDefault(SsrContext_1).default; } });
|
|
15
|
+
var useAsyncCollection_1 = require("./useAsyncCollection");
|
|
16
|
+
Object.defineProperty(exports, "useAsyncCollection", { enumerable: true, get: function () { return __importDefault(useAsyncCollection_1).default; } });
|
|
17
|
+
var useAsyncData_1 = require("./useAsyncData");
|
|
18
|
+
Object.defineProperty(exports, "useAsyncData", { enumerable: true, get: function () { return __importDefault(useAsyncData_1).default; } });
|
|
19
|
+
Object.defineProperty(exports, "newAsyncDataEnvelope", { enumerable: true, get: function () { return useAsyncData_1.newAsyncDataEnvelope; } });
|
|
20
|
+
var useGlobalState_1 = require("./useGlobalState");
|
|
21
|
+
Object.defineProperty(exports, "useGlobalState", { enumerable: true, get: function () { return __importDefault(useGlobalState_1).default; } });
|
|
22
|
+
var withGlobalStateType_1 = require("./withGlobalStateType");
|
|
23
|
+
Object.defineProperty(exports, "withGlobalStateType", { enumerable: true, get: function () { return __importDefault(withGlobalStateType_1).default; } });
|
|
@@ -1,43 +1,39 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Loads and uses an item in an async collection.
|
|
3
3
|
*/
|
|
4
|
-
|
|
5
|
-
import
|
|
6
|
-
|
|
4
|
+
import { type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
|
|
5
|
+
import { TypeLock } from './utils';
|
|
6
|
+
export type AsyncCollectionLoaderT<DataT> = (id: string, oldData: null | DataT) => DataT | Promise<DataT>;
|
|
7
7
|
/**
|
|
8
8
|
* Resolves and stores at the given `path` of global state elements of
|
|
9
9
|
* an asynchronous data collection. In other words, it is an auxiliar wrapper
|
|
10
10
|
* around {@link useAsyncData}, which uses a loader which resolves to different
|
|
11
11
|
* data, based on ID argument passed in, and stores data fetched for different
|
|
12
12
|
* IDs in the state.
|
|
13
|
-
* @param
|
|
14
|
-
* @param
|
|
13
|
+
* @param id ID of the collection item to load & use.
|
|
14
|
+
* @param path The global state path where entire collection should be
|
|
15
15
|
* stored.
|
|
16
|
-
* @param
|
|
16
|
+
* @param loader A loader function, which takes an
|
|
17
17
|
* ID of data to load, and resolves to the corresponding data.
|
|
18
|
-
* @param
|
|
19
|
-
* @param
|
|
18
|
+
* @param options Additional options.
|
|
19
|
+
* @param options.deps An array of dependencies, which trigger
|
|
20
20
|
* data reload when changed. Given dependency changes are watched shallowly
|
|
21
21
|
* (similarly to the standard React's
|
|
22
22
|
* [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
|
|
23
|
-
* @param
|
|
23
|
+
* @param options.noSSR If `true`, this hook won't load data during
|
|
24
24
|
* server-side rendering.
|
|
25
|
-
* @param
|
|
25
|
+
* @param options.garbageCollectAge The maximum age of data
|
|
26
26
|
* (in milliseconds), after which they are dropped from the state when the last
|
|
27
27
|
* component referencing them via `useAsyncData()` hook unmounts. Defaults to
|
|
28
28
|
* `maxage` option value.
|
|
29
|
-
* @param
|
|
29
|
+
* @param options.maxage The maximum age of
|
|
30
30
|
* data (in milliseconds) acceptable to the hook's caller. If loaded data are
|
|
31
31
|
* older than this value, `null` is returned instead. Defaults to 5 minutes.
|
|
32
|
-
* @param
|
|
32
|
+
* @param options.refreshAge The maximum age of data
|
|
33
33
|
* (in milliseconds), after which their refreshment will be triggered when
|
|
34
34
|
* any component referencing them via `useAsyncData()` hook (re-)renders.
|
|
35
35
|
* Defaults to `maxage` value.
|
|
36
|
-
* @return
|
|
37
|
-
* data: any,
|
|
38
|
-
* loading: boolean,
|
|
39
|
-
* timestamp: number
|
|
40
|
-
* }} Returns an object with three fields: `data` holds the actual result of
|
|
36
|
+
* @return Returns an object with three fields: `data` holds the actual result of
|
|
41
37
|
* last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
|
|
42
38
|
* is a boolean flag, which is `true` if data are being loaded (the hook is
|
|
43
39
|
* waiting for `loader` function resolution); `timestamp` (in milliseconds)
|
|
@@ -50,9 +46,6 @@ import useAsyncData from "./useAsyncData";
|
|
|
50
46
|
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
51
47
|
* `useAsyncData()` hooks logic.
|
|
52
48
|
*/
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return useAsyncData(itemPath, oldData => loader(id, oldData), options);
|
|
57
|
-
}
|
|
58
|
-
//# sourceMappingURL=useAsyncCollection.js.map
|
|
49
|
+
declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
|
|
50
|
+
declare function useAsyncCollection<Unlocked extends 0 | 1 = 0, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Unlocked, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Unlocked, void, DataT>>;
|
|
51
|
+
export default useAsyncCollection;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Loads and uses an item in an async collection.
|
|
4
|
+
*/
|
|
5
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
6
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
7
|
+
};
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
const useAsyncData_1 = __importDefault(require("./useAsyncData"));
|
|
10
|
+
function useAsyncCollection(id, path, loader, options = {}) {
|
|
11
|
+
const itemPath = path ? `${path}.${id}` : id;
|
|
12
|
+
return (0, useAsyncData_1.default)(itemPath, (oldData) => loader(id, oldData), options);
|
|
13
|
+
}
|
|
14
|
+
exports.default = useAsyncCollection;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads and uses async data into the GlobalState path.
|
|
3
|
+
*/
|
|
4
|
+
import { TypeLock } from './utils';
|
|
5
|
+
import { type ValueAtPathT } from './utils';
|
|
6
|
+
export type AsyncDataLoaderT<DataT> = (oldData: null | DataT) => DataT | Promise<DataT>;
|
|
7
|
+
export type AsyncDataEnvelopeT<DataT> = {
|
|
8
|
+
data: null | DataT;
|
|
9
|
+
numRefs: number;
|
|
10
|
+
operationId: string;
|
|
11
|
+
timestamp: number;
|
|
12
|
+
};
|
|
13
|
+
export declare function newAsyncDataEnvelope<DataT>(initialData?: DataT | null): AsyncDataEnvelopeT<DataT>;
|
|
14
|
+
export type UseAsyncDataOptionsT = {
|
|
15
|
+
deps?: unknown[];
|
|
16
|
+
garbageCollectAge?: number;
|
|
17
|
+
maxage?: number;
|
|
18
|
+
noSSR?: boolean;
|
|
19
|
+
refreshAge?: number;
|
|
20
|
+
};
|
|
21
|
+
export type UseAsyncDataResT<DataT> = {
|
|
22
|
+
data: DataT | null;
|
|
23
|
+
loading: boolean;
|
|
24
|
+
timestamp: number;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Resolves asynchronous data, and stores them at given `path` of global
|
|
28
|
+
* state. When multiple components rely on asynchronous data at the same `path`,
|
|
29
|
+
* the data are resolved once, and reused until their age is within specified
|
|
30
|
+
* bounds. Once the data are stale, the hook allows to refresh them. It also
|
|
31
|
+
* garbage-collects stale data from the global state when the last component
|
|
32
|
+
* relying on them is unmounted.
|
|
33
|
+
* @param path Dot-delimitered state path, where data envelop is
|
|
34
|
+
* stored.
|
|
35
|
+
* @param loader Asynchronous function which resolves (loads)
|
|
36
|
+
* data, which should be stored at the global state `path`. When multiple
|
|
37
|
+
* components
|
|
38
|
+
* use `useAsyncData()` hook for the same `path`, the library assumes that all
|
|
39
|
+
* hook instances are called with the same `loader` (_i.e._ whichever of these
|
|
40
|
+
* loaders is used to resolve async data, the result is acceptable to be reused
|
|
41
|
+
* in all related components).
|
|
42
|
+
* @param options Additional options.
|
|
43
|
+
* @param options.deps An array of dependencies, which trigger
|
|
44
|
+
* data reload when changed. Given dependency changes are watched shallowly
|
|
45
|
+
* (similarly to the standard React's
|
|
46
|
+
* [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
|
|
47
|
+
* @param options.noSSR If `true`, this hook won't load data during
|
|
48
|
+
* server-side rendering.
|
|
49
|
+
* @param options.garbageCollectAge The maximum age of data
|
|
50
|
+
* (in milliseconds), after which they are dropped from the state when the last
|
|
51
|
+
* component referencing them via `useAsyncData()` hook unmounts. Defaults to
|
|
52
|
+
* `maxage` option value.
|
|
53
|
+
* @param options.maxage The maximum age of
|
|
54
|
+
* data (in milliseconds) acceptable to the hook's caller. If loaded data are
|
|
55
|
+
* older than this value, `null` is returned instead. Defaults to 5 minutes.
|
|
56
|
+
* @param options.refreshAge The maximum age of data
|
|
57
|
+
* (in milliseconds), after which their refreshment will be triggered when
|
|
58
|
+
* any component referencing them via `useAsyncData()` hook (re-)renders.
|
|
59
|
+
* Defaults to `maxage` value.
|
|
60
|
+
* @return Returns an object with three fields: `data` holds the actual result of
|
|
61
|
+
* last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
|
|
62
|
+
* is a boolean flag, which is `true` if data are being loaded (the hook is
|
|
63
|
+
* waiting for `loader` function resolution); `timestamp` (in milliseconds)
|
|
64
|
+
* is Unix timestamp of related data currently loaded into the global state.
|
|
65
|
+
*
|
|
66
|
+
* Note that loaded data, if any, are stored at the given `path` of global state
|
|
67
|
+
* along with related meta-information, using slightly different state segment
|
|
68
|
+
* structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
|
|
69
|
+
* can be accessed, and even modified using other hooks,
|
|
70
|
+
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
71
|
+
* `useAsyncData()` hooks logic.
|
|
72
|
+
*/
|
|
73
|
+
export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined> = ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown> ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null> : void;
|
|
74
|
+
declare function useAsyncData<StateT, PathT extends null | string | undefined>(path: PathT, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
75
|
+
declare function useAsyncData<Unlocked extends 0 | 1 = 0, DataT = unknown>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Unlocked, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Unlocked, void, DataT>>;
|
|
76
|
+
export default useAsyncData;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Loads and uses async data into the GlobalState path.
|
|
4
|
+
*/
|
|
5
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
6
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
7
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
8
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
9
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
10
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
11
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
12
|
+
});
|
|
13
|
+
};
|
|
14
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
15
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
16
|
+
};
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.newAsyncDataEnvelope = void 0;
|
|
19
|
+
const lodash_1 = require("lodash");
|
|
20
|
+
const react_1 = require("react");
|
|
21
|
+
const uuid_1 = require("uuid");
|
|
22
|
+
const js_utils_1 = require("@dr.pogodin/js-utils");
|
|
23
|
+
const GlobalStateProvider_1 = require("./GlobalStateProvider");
|
|
24
|
+
const useGlobalState_1 = __importDefault(require("./useGlobalState"));
|
|
25
|
+
const utils_1 = require("./utils");
|
|
26
|
+
const DEFAULT_MAXAGE = 5 * js_utils_1.MIN_MS; // 5 minutes.
|
|
27
|
+
function newAsyncDataEnvelope(initialData = null) {
|
|
28
|
+
return {
|
|
29
|
+
data: initialData,
|
|
30
|
+
numRefs: 0,
|
|
31
|
+
operationId: '',
|
|
32
|
+
timestamp: 0,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
exports.newAsyncDataEnvelope = newAsyncDataEnvelope;
|
|
36
|
+
/**
|
|
37
|
+
* Executes the data loading operation.
|
|
38
|
+
* @param path Data segment path inside the global state.
|
|
39
|
+
* @param loader Data loader.
|
|
40
|
+
* @param globalState The global state instance.
|
|
41
|
+
* @param oldData Optional. Previously fetched data, currently stored in
|
|
42
|
+
* the state, if already fetched by the caller; otherwise, they will be fetched
|
|
43
|
+
* by the load() function itself.
|
|
44
|
+
* @param opIdPrefix operationId prefix to use, which should be
|
|
45
|
+
* 'C' at the client-side (default), or 'S' at the server-side (within SSR
|
|
46
|
+
* context).
|
|
47
|
+
* @return Resolves once the operation is done.
|
|
48
|
+
* @ignore
|
|
49
|
+
*/
|
|
50
|
+
function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
|
|
51
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
52
|
+
if (process.env.NODE_ENV !== 'production' && (0, utils_1.isDebugMode)()) {
|
|
53
|
+
/* eslint-disable no-console */
|
|
54
|
+
console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
|
|
55
|
+
/* eslint-enable no-console */
|
|
56
|
+
}
|
|
57
|
+
const operationId = opIdPrefix + (0, uuid_1.v4)();
|
|
58
|
+
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
59
|
+
globalState.set(operationIdPath, operationId);
|
|
60
|
+
const data = yield loader(oldData || (globalState.get(path)).data);
|
|
61
|
+
const state = globalState.get(path);
|
|
62
|
+
if (operationId === state.operationId) {
|
|
63
|
+
if (process.env.NODE_ENV !== 'production' && (0, utils_1.isDebugMode)()) {
|
|
64
|
+
/* eslint-disable no-console */
|
|
65
|
+
console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
|
|
66
|
+
console.log('Data:', (0, lodash_1.cloneDeep)(data));
|
|
67
|
+
/* eslint-enable no-console */
|
|
68
|
+
}
|
|
69
|
+
globalState.set(path, Object.assign(Object.assign({}, state), { data, operationId: '', timestamp: Date.now() }));
|
|
70
|
+
if (process.env.NODE_ENV !== 'production' && (0, utils_1.isDebugMode)()) {
|
|
71
|
+
/* eslint-disable no-console */
|
|
72
|
+
console.groupEnd();
|
|
73
|
+
/* eslint-enable no-console */
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
function useAsyncData(path, loader, options = {}) {
|
|
79
|
+
const maxage = options.maxage === undefined
|
|
80
|
+
? DEFAULT_MAXAGE : options.maxage;
|
|
81
|
+
const refreshAge = options.refreshAge === undefined
|
|
82
|
+
? maxage : options.refreshAge;
|
|
83
|
+
const garbageCollectAge = options.garbageCollectAge === undefined
|
|
84
|
+
? maxage : options.garbageCollectAge;
|
|
85
|
+
// Note: here we can't depend on useGlobalState() to init the initial value,
|
|
86
|
+
// because that way we'll have issues with SSR (see details below).
|
|
87
|
+
const globalState = (0, GlobalStateProvider_1.getGlobalState)();
|
|
88
|
+
const state = globalState.get(path, {
|
|
89
|
+
initialValue: newAsyncDataEnvelope(),
|
|
90
|
+
});
|
|
91
|
+
if (globalState.ssrContext && !options.noSSR) {
|
|
92
|
+
if (!state.timestamp && !state.operationId) {
|
|
93
|
+
globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
// This takes care about the client-side reference counting, and garbage
|
|
98
|
+
// collection.
|
|
99
|
+
//
|
|
100
|
+
// Note: the Rules of Hook below are violated by conditional call to a hook,
|
|
101
|
+
// but as the condition is actually server-side or client-side environment,
|
|
102
|
+
// it is effectively non-conditional at the runtime.
|
|
103
|
+
//
|
|
104
|
+
// TODO: Though, maybe there is a way to refactor it into a cleaner code.
|
|
105
|
+
// The same applies to other useEffect() hooks below.
|
|
106
|
+
(0, react_1.useEffect)(() => {
|
|
107
|
+
const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
|
|
108
|
+
const numRefs = globalState.get(numRefsPath);
|
|
109
|
+
globalState.set(numRefsPath, numRefs + 1);
|
|
110
|
+
return () => {
|
|
111
|
+
const state2 = globalState.get(path);
|
|
112
|
+
if (state2.numRefs === 1
|
|
113
|
+
&& garbageCollectAge < Date.now() - state2.timestamp) {
|
|
114
|
+
if (process.env.NODE_ENV !== 'production' && (0, utils_1.isDebugMode)()) {
|
|
115
|
+
/* eslint-disable no-console */
|
|
116
|
+
console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
|
|
117
|
+
/* eslint-enable no-console */
|
|
118
|
+
}
|
|
119
|
+
globalState.set(path, Object.assign(Object.assign({}, state2), { data: null, numRefs: 0, timestamp: 0 }));
|
|
120
|
+
}
|
|
121
|
+
else
|
|
122
|
+
globalState.set(numRefsPath, state2.numRefs - 1);
|
|
123
|
+
};
|
|
124
|
+
}, [garbageCollectAge, globalState, path]);
|
|
125
|
+
// Note: a bunch of Rules of Hooks ignored belows because in our very
|
|
126
|
+
// special case the otherwise wrong behavior is actually what we need.
|
|
127
|
+
// Data loading and refreshing.
|
|
128
|
+
let loadTriggered = false;
|
|
129
|
+
(0, react_1.useEffect)(() => {
|
|
130
|
+
const state2 = globalState.get(path);
|
|
131
|
+
if (refreshAge < Date.now() - state2.timestamp
|
|
132
|
+
&& (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
|
|
133
|
+
load(path, loader, globalState, state2.data);
|
|
134
|
+
loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
const deps = options.deps || [];
|
|
138
|
+
(0, react_1.useEffect)(() => {
|
|
139
|
+
if (!loadTriggered && deps.length)
|
|
140
|
+
load(path, loader, globalState, null);
|
|
141
|
+
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
|
|
142
|
+
}
|
|
143
|
+
const [localState] = (0, useGlobalState_1.default)(path, newAsyncDataEnvelope());
|
|
144
|
+
return {
|
|
145
|
+
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
146
|
+
loading: Boolean(localState.operationId),
|
|
147
|
+
timestamp: localState.timestamp,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
exports.default = useAsyncData;
|
|
@@ -1,10 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import { getGlobalState } from "./GlobalStateProvider";
|
|
6
|
-
import { isDebugMode } from "./utils";
|
|
7
|
-
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import { type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
|
|
3
|
+
export type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;
|
|
4
|
+
export type UseGlobalStateResT<T> = [T, SetterT<T>];
|
|
8
5
|
/**
|
|
9
6
|
* The primary hook for interacting with the global state, modeled after
|
|
10
7
|
* the standard React's
|
|
@@ -25,14 +22,14 @@ import { isDebugMode } from "./utils";
|
|
|
25
22
|
* state values are "fixed", and all changes becomes visible at once in the
|
|
26
23
|
* next triggered rendering pass.
|
|
27
24
|
*
|
|
28
|
-
* @param
|
|
25
|
+
* @param path Dot-delimitered state path. It can be undefined to
|
|
29
26
|
* subscribe for entire state.
|
|
30
27
|
*
|
|
31
28
|
* Under-the-hood state values are read and written using `lodash`
|
|
32
29
|
* [_.get()](https://lodash.com/docs/4.17.15#get) and
|
|
33
30
|
* [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
|
|
34
31
|
* to access state paths which have not been created before.
|
|
35
|
-
* @param
|
|
32
|
+
* @param initialValue Initial value to set at the `path`, or its
|
|
36
33
|
* factory:
|
|
37
34
|
* - If a function is given, it will act similar to
|
|
38
35
|
* [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
|
|
@@ -40,7 +37,7 @@ import { isDebugMode } from "./utils";
|
|
|
40
37
|
* and the value it returns will be written to the `path`.
|
|
41
38
|
* - Otherwise, the given value itself will be written to the `path`,
|
|
42
39
|
* if the current value at `path` is `undefined`.
|
|
43
|
-
* @return
|
|
40
|
+
* @return It returs an array with two elements: `[value, setValue]`:
|
|
44
41
|
*
|
|
45
42
|
* - The `value` is the current value at given `path`.
|
|
46
43
|
*
|
|
@@ -55,55 +52,7 @@ import { isDebugMode } from "./utils";
|
|
|
55
52
|
* Also, similar to the standard React's state setters, `setValue()` is
|
|
56
53
|
* stable function: it does not change between component re-renders.
|
|
57
54
|
*/
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
callbacks: [],
|
|
63
|
-
setter: value => {
|
|
64
|
-
const rc = ref.current;
|
|
65
|
-
const newState = isFunction(value) ? value(rc.state) : value;
|
|
66
|
-
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
67
|
-
/* eslint-disable no-console */
|
|
68
|
-
console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
|
|
69
|
-
console.log('New value:', cloneDeep(newState));
|
|
70
|
-
console.groupEnd();
|
|
71
|
-
/* eslint-enable no-console */
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
rc.globalState.set(rc.path, newState);
|
|
75
|
-
},
|
|
76
|
-
watcher: () => {
|
|
77
|
-
const rc = ref.current;
|
|
78
|
-
const state = rc.globalState.get(rc.path);
|
|
79
|
-
if (state !== rc.state) {
|
|
80
|
-
for (let i = 0; i < rc.callbacks.length; ++i) {
|
|
81
|
-
rc.callbacks[i]();
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
const rc = ref.current;
|
|
88
|
-
const globalState = getGlobalState();
|
|
89
|
-
rc.globalState = globalState;
|
|
90
|
-
rc.path = path;
|
|
91
|
-
rc.state = useSyncExternalStore(cb => {
|
|
92
|
-
rc.callbacks.push(cb);
|
|
93
|
-
}, () => rc.globalState.get(rc.path, {
|
|
94
|
-
initialValue
|
|
95
|
-
}), () => rc.globalState.get(rc.path, {
|
|
96
|
-
initialValue,
|
|
97
|
-
initialState: true
|
|
98
|
-
}));
|
|
99
|
-
useEffect(() => {
|
|
100
|
-
globalState.watch(rc.watcher);
|
|
101
|
-
rc.watcher();
|
|
102
|
-
return () => globalState.unWatch(rc.watcher);
|
|
103
|
-
}, [globalState, rc]);
|
|
104
|
-
useEffect(() => {
|
|
105
|
-
rc.watcher();
|
|
106
|
-
}, [path, rc]);
|
|
107
|
-
return [rc.state, rc.setter];
|
|
108
|
-
}
|
|
109
|
-
//# sourceMappingURL=useGlobalState.js.map
|
|
55
|
+
declare function useGlobalState<StateT>(): UseGlobalStateResT<StateT>;
|
|
56
|
+
declare function useGlobalState<StateT, PathT extends null | string | undefined>(path: PathT, initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;
|
|
57
|
+
declare function useGlobalState<Unlocked extends 0 | 1 = 0, ValueT = void>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Unlocked, never, ValueT>>): UseGlobalStateResT<TypeLock<Unlocked, void, ValueT>>;
|
|
58
|
+
export default useGlobalState;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Hook for updates of global state.
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
const lodash_1 = require("lodash");
|
|
5
|
+
const react_1 = require("react");
|
|
6
|
+
const js_utils_1 = require("@dr.pogodin/js-utils");
|
|
7
|
+
const GlobalStateProvider_1 = require("./GlobalStateProvider");
|
|
8
|
+
const utils_1 = require("./utils");
|
|
9
|
+
function useGlobalState(path, initialValue) {
|
|
10
|
+
const globalState = (0, GlobalStateProvider_1.getGlobalState)();
|
|
11
|
+
const ref = (0, react_1.useRef)();
|
|
12
|
+
const rc = ref.current || {
|
|
13
|
+
emitter: new js_utils_1.Emitter(),
|
|
14
|
+
globalState,
|
|
15
|
+
path,
|
|
16
|
+
setter: (value) => {
|
|
17
|
+
const newState = (0, lodash_1.isFunction)(value) ? value(rc.state) : value;
|
|
18
|
+
if (process.env.NODE_ENV !== 'production' && (0, utils_1.isDebugMode)()) {
|
|
19
|
+
/* eslint-disable no-console */
|
|
20
|
+
console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
|
|
21
|
+
console.log('New value:', (0, lodash_1.cloneDeep)(newState));
|
|
22
|
+
console.groupEnd();
|
|
23
|
+
/* eslint-enable no-console */
|
|
24
|
+
}
|
|
25
|
+
rc.globalState.set(rc.path, newState);
|
|
26
|
+
},
|
|
27
|
+
state: (0, lodash_1.isFunction)(initialValue) ? initialValue() : initialValue,
|
|
28
|
+
watcher: () => {
|
|
29
|
+
const state = rc.globalState.get(rc.path);
|
|
30
|
+
if (state !== rc.state)
|
|
31
|
+
rc.emitter.emit();
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
ref.current = rc;
|
|
35
|
+
rc.globalState = globalState;
|
|
36
|
+
rc.path = path;
|
|
37
|
+
rc.state = (0, react_1.useSyncExternalStore)((cb) => rc.emitter.addListener(cb), () => rc.globalState.get(rc.path, { initialValue }), () => rc.globalState.get(rc.path, { initialValue, initialState: true }));
|
|
38
|
+
(0, react_1.useEffect)(() => {
|
|
39
|
+
const { watcher } = ref.current;
|
|
40
|
+
globalState.watch(watcher);
|
|
41
|
+
watcher();
|
|
42
|
+
return () => globalState.unWatch(watcher);
|
|
43
|
+
}, [globalState]);
|
|
44
|
+
(0, react_1.useEffect)(() => {
|
|
45
|
+
ref.current.watcher();
|
|
46
|
+
}, [path]);
|
|
47
|
+
return [rc.state, rc.setter];
|
|
48
|
+
}
|
|
49
|
+
exports.default = useGlobalState;
|
package/build/utils.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type GetFieldType } from 'lodash';
|
|
2
|
+
export type CallbackT = () => void;
|
|
3
|
+
export type TypeLock<Unlocked extends 0 | 1, LockedT extends never | void, UnlockedT> = Unlocked extends 0 ? LockedT : UnlockedT;
|
|
4
|
+
/**
|
|
5
|
+
* Given the type of state, `StateT`, and the type of state path, `PathT`,
|
|
6
|
+
* it evaluates the type of value at that path of the state, if it can be
|
|
7
|
+
* evaluated from the path type (it is possible when `PathT` is a string
|
|
8
|
+
* literal type, and `StateT` elements along this path have appropriate
|
|
9
|
+
* types); otherwise it falls back to the specified `UnknownT` type,
|
|
10
|
+
* which should be set either `never` (for input arguments), or `void`
|
|
11
|
+
* (for return types) - `never` and `void` in those places forbid assignments,
|
|
12
|
+
* and are not auto-inferred to more permissible types.
|
|
13
|
+
*
|
|
14
|
+
* BEWARE: When StateT is any the construct resolves to any for any string
|
|
15
|
+
* paths.
|
|
16
|
+
*/
|
|
17
|
+
export type ValueAtPathT<StateT, PathT extends null | string | undefined, UnknownT extends never | undefined | void> = unknown extends StateT ? UnknownT : string extends PathT ? UnknownT : PathT extends null | undefined ? StateT : GetFieldType<StateT, PathT> extends undefined ? UnknownT : GetFieldType<StateT, PathT>;
|
|
18
|
+
export type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);
|
|
19
|
+
/**
|
|
20
|
+
* Returns 'true' if debug logging should be performed; 'false' otherwise.
|
|
21
|
+
*
|
|
22
|
+
* BEWARE: The actual safeguards for the debug logging still should read
|
|
23
|
+
* if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
24
|
+
* // Some debug logging
|
|
25
|
+
* }
|
|
26
|
+
* to ensure that debug code is stripped out by Webpack in production mode.
|
|
27
|
+
*
|
|
28
|
+
* @returns
|
|
29
|
+
* @ignore
|
|
30
|
+
*/
|
|
31
|
+
export declare function isDebugMode(): boolean;
|