@dr.pogodin/react-global-state 0.10.0-alpha.1 → 0.10.0-alpha.3
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 -327
- package/build/common/GlobalState.js +219 -0
- package/build/common/GlobalState.js.map +1 -0
- package/build/common/GlobalStateProvider.js +101 -0
- package/build/common/GlobalStateProvider.js.map +1 -0
- package/build/common/SsrContext.js +15 -0
- package/build/common/SsrContext.js.map +1 -0
- package/build/common/index.js +76 -0
- package/build/common/index.js.map +1 -0
- package/build/common/useAsyncCollection.js +61 -0
- package/build/common/useAsyncCollection.js.map +1 -0
- package/build/common/useAsyncData.js +204 -0
- package/build/common/useAsyncData.js.map +1 -0
- package/build/common/useGlobalState.js +113 -0
- package/build/common/useGlobalState.js.map +1 -0
- package/build/common/utils.js +44 -0
- package/build/common/utils.js.map +1 -0
- package/build/common/withGlobalStateType.js +42 -0
- package/build/common/withGlobalStateType.js.map +1 -0
- package/build/module/GlobalState.js +230 -0
- package/build/module/GlobalState.js.map +1 -0
- package/build/module/GlobalStateProvider.js +94 -0
- package/build/module/GlobalStateProvider.js.map +1 -0
- package/build/module/SsrContext.js +9 -0
- package/build/module/SsrContext.js.map +1 -0
- package/build/module/index.js +8 -0
- package/build/module/index.js.map +1 -0
- package/build/module/useAsyncCollection.js +56 -0
- package/build/module/useAsyncCollection.js.map +1 -0
- package/build/module/useAsyncData.js +199 -0
- package/build/module/useAsyncData.js.map +1 -0
- package/build/module/useGlobalState.js +108 -0
- package/build/module/useGlobalState.js.map +1 -0
- package/build/module/utils.js +35 -0
- package/build/module/utils.js.map +1 -0
- package/build/module/withGlobalStateType.js +35 -0
- package/build/module/withGlobalStateType.js.map +1 -0
- package/build/types/GlobalState.d.ts +75 -0
- package/build/types/GlobalStateProvider.d.ts +55 -0
- package/build/types/SsrContext.d.ts +6 -0
- package/build/types/index.d.ts +8 -0
- package/build/types/useAsyncCollection.d.ts +51 -0
- package/build/types/useAsyncData.d.ts +75 -0
- package/build/types/useGlobalState.d.ts +58 -0
- package/build/types/utils.d.ts +34 -0
- package/build/types/withGlobalStateType.d.ts +29 -0
- package/package.json +42 -41
- package/src/GlobalState.ts +283 -0
- package/src/GlobalStateProvider.tsx +127 -0
- package/src/SsrContext.ts +11 -0
- package/src/index.ts +33 -0
- package/src/useAsyncCollection.ts +96 -0
- package/src/useAsyncData.ts +295 -0
- package/src/useGlobalState.ts +156 -0
- package/src/utils.ts +64 -0
- package/src/withGlobalStateType.ts +170 -0
- package/tsconfig.json +9 -3
- package/tsconfig.types.json +14 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/* eslint-disable react/prop-types */
|
|
2
|
+
|
|
3
|
+
import { isFunction } from 'lodash';
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
type ReactNode,
|
|
7
|
+
createContext,
|
|
8
|
+
useContext,
|
|
9
|
+
useRef,
|
|
10
|
+
} from 'react';
|
|
11
|
+
|
|
12
|
+
import GlobalState from './GlobalState';
|
|
13
|
+
import SsrContext from './SsrContext';
|
|
14
|
+
|
|
15
|
+
import { type ValueOrInitializerT } from './utils';
|
|
16
|
+
|
|
17
|
+
const context = createContext<GlobalState<unknown> | null>(null);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Gets {@link GlobalState} instance from the context. In most cases
|
|
21
|
+
* you should use {@link useGlobalState}, and other hooks to interact with
|
|
22
|
+
* the global state, instead of accessing it directly.
|
|
23
|
+
* @return
|
|
24
|
+
*/
|
|
25
|
+
export function getGlobalState<
|
|
26
|
+
StateT,
|
|
27
|
+
SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
|
|
28
|
+
>(): GlobalState<StateT, SsrContextT> {
|
|
29
|
+
// Here Rules of Hooks are violated because "getGlobalState()" does not follow
|
|
30
|
+
// convention that hook names should start with use... This is intentional in
|
|
31
|
+
// our case, as getGlobalState() hook is intended for advance scenarious,
|
|
32
|
+
// while the normal interaction with the global state should happen via
|
|
33
|
+
// another hook, useGlobalState().
|
|
34
|
+
/* eslint-disable react-hooks/rules-of-hooks */
|
|
35
|
+
const globalState = useContext(context);
|
|
36
|
+
/* eslint-enable react-hooks/rules-of-hooks */
|
|
37
|
+
if (!globalState) throw new Error('Missing GlobalStateProvider');
|
|
38
|
+
return globalState as GlobalState<StateT, SsrContextT>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @category Hooks
|
|
43
|
+
* @desc Gets SSR context.
|
|
44
|
+
* @param throwWithoutSsrContext If `true` (default),
|
|
45
|
+
* this hook will throw if no SSR context is attached to the global state;
|
|
46
|
+
* set `false` to not throw in such case. In either case the hook will throw
|
|
47
|
+
* if the {@link <GlobalStateProvider>} (hence the state) is missing.
|
|
48
|
+
* @returns SSR context.
|
|
49
|
+
* @throws
|
|
50
|
+
* - If current component has no parent {@link <GlobalStateProvider>}
|
|
51
|
+
* in the rendered React tree.
|
|
52
|
+
* - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
|
|
53
|
+
* to the global state provided by {@link <GlobalStateProvider>}.
|
|
54
|
+
*/
|
|
55
|
+
export function getSsrContext<
|
|
56
|
+
SsrContextT extends SsrContext<unknown>,
|
|
57
|
+
>(
|
|
58
|
+
throwWithoutSsrContext = true,
|
|
59
|
+
): SsrContextT | undefined {
|
|
60
|
+
const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();
|
|
61
|
+
if (!ssrContext && throwWithoutSsrContext) {
|
|
62
|
+
throw new Error('No SSR context found');
|
|
63
|
+
}
|
|
64
|
+
return ssrContext;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
type NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {
|
|
68
|
+
initialState: ValueOrInitializerT<StateT>,
|
|
69
|
+
ssrContext?: SsrContextT;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
type GlobalStateProviderProps<
|
|
73
|
+
StateT,
|
|
74
|
+
SsrContextT extends SsrContext<StateT>,
|
|
75
|
+
> = {
|
|
76
|
+
children?: ReactNode;
|
|
77
|
+
} & (NewStateProps<StateT, SsrContextT> | {
|
|
78
|
+
stateProxy: true | GlobalState<StateT, SsrContextT>;
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Provides global state to its children.
|
|
83
|
+
* @param prop.children Component children, which will be provided with
|
|
84
|
+
* the global state, and rendered in place of the provider.
|
|
85
|
+
* @param prop.initialState Initial content of the global state.
|
|
86
|
+
* @param prop.ssrContext Server-side rendering (SSR) context.
|
|
87
|
+
* @param prop.stateProxy This option is useful for code
|
|
88
|
+
* splitting and SSR implementation:
|
|
89
|
+
* - If `true`, this provider instance will fetch and reuse the global state
|
|
90
|
+
* from a parent provider.
|
|
91
|
+
* - If `GlobalState` instance, it will be used by this provider.
|
|
92
|
+
* - If not given, a new `GlobalState` instance will be created and used.
|
|
93
|
+
*/
|
|
94
|
+
export default function GlobalStateProvider<
|
|
95
|
+
StateT,
|
|
96
|
+
SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
|
|
97
|
+
>(
|
|
98
|
+
{ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,
|
|
99
|
+
) {
|
|
100
|
+
const state = useRef<GlobalState<StateT, SsrContextT>>();
|
|
101
|
+
if (!state.current) {
|
|
102
|
+
// NOTE: The last part of condition, "&& rest.stateProxy", is needed for
|
|
103
|
+
// graceful compatibility with JavaScript - if "undefined" stateProxy value
|
|
104
|
+
// is given, we want to follow the second branch, which creates a new
|
|
105
|
+
// GlobalState with whatever intiialState given.
|
|
106
|
+
if ('stateProxy' in rest && rest.stateProxy) {
|
|
107
|
+
if (rest.stateProxy === true) state.current = getGlobalState();
|
|
108
|
+
else state.current = rest.stateProxy;
|
|
109
|
+
} else {
|
|
110
|
+
const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;
|
|
111
|
+
|
|
112
|
+
state.current = new GlobalState<StateT, SsrContextT>(
|
|
113
|
+
isFunction(initialState) ? initialState() : initialState,
|
|
114
|
+
ssrContext,
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return (
|
|
119
|
+
<context.Provider value={state.current}>
|
|
120
|
+
{children}
|
|
121
|
+
</context.Provider>
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
GlobalStateProvider.defaultProps = {
|
|
126
|
+
children: undefined,
|
|
127
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export { default as GlobalState } from './GlobalState';
|
|
2
|
+
|
|
3
|
+
export {
|
|
4
|
+
default as GlobalStateProvider,
|
|
5
|
+
getGlobalState,
|
|
6
|
+
getSsrContext,
|
|
7
|
+
} from './GlobalStateProvider';
|
|
8
|
+
|
|
9
|
+
export { default as SsrContext } from './SsrContext';
|
|
10
|
+
|
|
11
|
+
export {
|
|
12
|
+
type AsyncCollectionLoaderT,
|
|
13
|
+
default as useAsyncCollection,
|
|
14
|
+
} from './useAsyncCollection';
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
type AsyncDataEnvelopeT,
|
|
18
|
+
type AsyncDataLoaderT,
|
|
19
|
+
type UseAsyncDataOptionsT,
|
|
20
|
+
type UseAsyncDataResT,
|
|
21
|
+
default as useAsyncData,
|
|
22
|
+
newAsyncDataEnvelope,
|
|
23
|
+
} from './useAsyncData';
|
|
24
|
+
|
|
25
|
+
export {
|
|
26
|
+
type SetterT,
|
|
27
|
+
type UseGlobalStateResT,
|
|
28
|
+
default as useGlobalState,
|
|
29
|
+
} from './useGlobalState';
|
|
30
|
+
|
|
31
|
+
export { type ForceT, type ValueOrInitializerT } from './utils';
|
|
32
|
+
|
|
33
|
+
export { default as withGlobalStateType } from './withGlobalStateType';
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads and uses an item in an async collection.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import useAsyncData, {
|
|
6
|
+
type DataInEnvelopeAtPathT,
|
|
7
|
+
type UseAsyncDataOptionsT,
|
|
8
|
+
type UseAsyncDataResT,
|
|
9
|
+
} from './useAsyncData';
|
|
10
|
+
|
|
11
|
+
import { type ForceT, type TypeLock } from './utils';
|
|
12
|
+
|
|
13
|
+
export type AsyncCollectionLoaderT<DataT> =
|
|
14
|
+
(id: string, oldData: null | DataT) => DataT | Promise<DataT>;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Resolves and stores at the given `path` of global state elements of
|
|
18
|
+
* an asynchronous data collection. In other words, it is an auxiliar wrapper
|
|
19
|
+
* around {@link useAsyncData}, which uses a loader which resolves to different
|
|
20
|
+
* data, based on ID argument passed in, and stores data fetched for different
|
|
21
|
+
* IDs in the state.
|
|
22
|
+
* @param id ID of the collection item to load & use.
|
|
23
|
+
* @param path The global state path where entire collection should be
|
|
24
|
+
* stored.
|
|
25
|
+
* @param loader A loader function, which takes an
|
|
26
|
+
* ID of data to load, and resolves to the corresponding data.
|
|
27
|
+
* @param options Additional options.
|
|
28
|
+
* @param options.deps An array of dependencies, which trigger
|
|
29
|
+
* data reload when changed. Given dependency changes are watched shallowly
|
|
30
|
+
* (similarly to the standard React's
|
|
31
|
+
* [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
|
|
32
|
+
* @param options.noSSR If `true`, this hook won't load data during
|
|
33
|
+
* server-side rendering.
|
|
34
|
+
* @param options.garbageCollectAge The maximum age of data
|
|
35
|
+
* (in milliseconds), after which they are dropped from the state when the last
|
|
36
|
+
* component referencing them via `useAsyncData()` hook unmounts. Defaults to
|
|
37
|
+
* `maxage` option value.
|
|
38
|
+
* @param options.maxage The maximum age of
|
|
39
|
+
* data (in milliseconds) acceptable to the hook's caller. If loaded data are
|
|
40
|
+
* older than this value, `null` is returned instead. Defaults to 5 minutes.
|
|
41
|
+
* @param options.refreshAge The maximum age of data
|
|
42
|
+
* (in milliseconds), after which their refreshment will be triggered when
|
|
43
|
+
* any component referencing them via `useAsyncData()` hook (re-)renders.
|
|
44
|
+
* Defaults to `maxage` value.
|
|
45
|
+
* @return Returns an object with three fields: `data` holds the actual result of
|
|
46
|
+
* last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
|
|
47
|
+
* is a boolean flag, which is `true` if data are being loaded (the hook is
|
|
48
|
+
* waiting for `loader` function resolution); `timestamp` (in milliseconds)
|
|
49
|
+
* is Unix timestamp of related data currently loaded into the global state.
|
|
50
|
+
*
|
|
51
|
+
* Note that loaded data, if any, are stored at the given `path` of global state
|
|
52
|
+
* along with related meta-information, using slightly different state segment
|
|
53
|
+
* structure (see {@link AsyncDataEnvelope}). That segment of the global state
|
|
54
|
+
* can be accessed, and even modified using other hooks,
|
|
55
|
+
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
56
|
+
* `useAsyncData()` hooks logic.
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
function useAsyncCollection<
|
|
60
|
+
StateT,
|
|
61
|
+
PathT extends null | string | undefined,
|
|
62
|
+
IdT extends string,
|
|
63
|
+
>(
|
|
64
|
+
id: IdT,
|
|
65
|
+
path: PathT,
|
|
66
|
+
loader: AsyncCollectionLoaderT<
|
|
67
|
+
DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>
|
|
68
|
+
>,
|
|
69
|
+
options?: UseAsyncDataOptionsT,
|
|
70
|
+
): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
|
|
71
|
+
|
|
72
|
+
function useAsyncCollection<
|
|
73
|
+
Forced extends ForceT | false = false,
|
|
74
|
+
DataT = unknown,
|
|
75
|
+
>(
|
|
76
|
+
id: string,
|
|
77
|
+
path: null | string | undefined,
|
|
78
|
+
loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,
|
|
79
|
+
options?: UseAsyncDataOptionsT,
|
|
80
|
+
): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
81
|
+
|
|
82
|
+
function useAsyncCollection<DataT>(
|
|
83
|
+
id: string,
|
|
84
|
+
path: null | string | undefined,
|
|
85
|
+
loader: AsyncCollectionLoaderT<DataT>,
|
|
86
|
+
options: UseAsyncDataOptionsT = {},
|
|
87
|
+
): UseAsyncDataResT<DataT> {
|
|
88
|
+
const itemPath = path ? `${path}.${id}` : id;
|
|
89
|
+
return useAsyncData<ForceT, DataT>(
|
|
90
|
+
itemPath,
|
|
91
|
+
(oldData: null | DataT) => loader(id, oldData),
|
|
92
|
+
options,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export default useAsyncCollection;
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads and uses async data into the GlobalState path.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { cloneDeep } from 'lodash';
|
|
6
|
+
import { useEffect } from 'react';
|
|
7
|
+
import { v4 as uuid } from 'uuid';
|
|
8
|
+
|
|
9
|
+
import { MIN_MS } from '@dr.pogodin/js-utils';
|
|
10
|
+
|
|
11
|
+
import { getGlobalState } from './GlobalStateProvider';
|
|
12
|
+
import useGlobalState from './useGlobalState';
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
type ForceT,
|
|
16
|
+
type TypeLock,
|
|
17
|
+
type ValueAtPathT,
|
|
18
|
+
isDebugMode,
|
|
19
|
+
} from './utils';
|
|
20
|
+
|
|
21
|
+
import GlobalState from './GlobalState';
|
|
22
|
+
import SsrContext from './SsrContext';
|
|
23
|
+
|
|
24
|
+
const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
|
|
25
|
+
|
|
26
|
+
export type AsyncDataLoaderT<DataT>
|
|
27
|
+
= (oldData: null | DataT) => DataT | Promise<DataT>;
|
|
28
|
+
|
|
29
|
+
export type AsyncDataEnvelopeT<DataT> = {
|
|
30
|
+
data: null | DataT;
|
|
31
|
+
numRefs: number;
|
|
32
|
+
operationId: string;
|
|
33
|
+
timestamp: number;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export function newAsyncDataEnvelope<DataT>(
|
|
37
|
+
initialData: DataT | null = null,
|
|
38
|
+
): AsyncDataEnvelopeT<DataT> {
|
|
39
|
+
return {
|
|
40
|
+
data: initialData,
|
|
41
|
+
numRefs: 0,
|
|
42
|
+
operationId: '',
|
|
43
|
+
timestamp: 0,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type UseAsyncDataOptionsT = {
|
|
48
|
+
deps?: unknown[];
|
|
49
|
+
garbageCollectAge?: number;
|
|
50
|
+
maxage?: number;
|
|
51
|
+
noSSR?: boolean;
|
|
52
|
+
refreshAge?: number;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export type UseAsyncDataResT<DataT> = {
|
|
56
|
+
data: DataT | null;
|
|
57
|
+
loading: boolean;
|
|
58
|
+
timestamp: number;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Executes the data loading operation.
|
|
63
|
+
* @param path Data segment path inside the global state.
|
|
64
|
+
* @param loader Data loader.
|
|
65
|
+
* @param globalState The global state instance.
|
|
66
|
+
* @param oldData Optional. Previously fetched data, currently stored in
|
|
67
|
+
* the state, if already fetched by the caller; otherwise, they will be fetched
|
|
68
|
+
* by the load() function itself.
|
|
69
|
+
* @param opIdPrefix operationId prefix to use, which should be
|
|
70
|
+
* 'C' at the client-side (default), or 'S' at the server-side (within SSR
|
|
71
|
+
* context).
|
|
72
|
+
* @return Resolves once the operation is done.
|
|
73
|
+
* @ignore
|
|
74
|
+
*/
|
|
75
|
+
async function load<DataT>(
|
|
76
|
+
path: null | string | undefined,
|
|
77
|
+
loader: AsyncDataLoaderT<DataT>,
|
|
78
|
+
globalState: GlobalState<unknown, SsrContext<unknown>>,
|
|
79
|
+
oldData: DataT | null,
|
|
80
|
+
opIdPrefix: 'C' | 'S' = 'C',
|
|
81
|
+
): Promise<void> {
|
|
82
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
83
|
+
/* eslint-disable no-console */
|
|
84
|
+
console.log(
|
|
85
|
+
`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`,
|
|
86
|
+
);
|
|
87
|
+
/* eslint-enable no-console */
|
|
88
|
+
}
|
|
89
|
+
const operationId = opIdPrefix + uuid();
|
|
90
|
+
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
91
|
+
globalState.set<ForceT, string>(operationIdPath, operationId);
|
|
92
|
+
const data = await loader(
|
|
93
|
+
oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,
|
|
94
|
+
);
|
|
95
|
+
const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);
|
|
96
|
+
if (operationId === state.operationId) {
|
|
97
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
98
|
+
/* eslint-disable no-console */
|
|
99
|
+
console.groupCollapsed(
|
|
100
|
+
`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${
|
|
101
|
+
path || ''
|
|
102
|
+
}"`,
|
|
103
|
+
);
|
|
104
|
+
console.log('Data:', cloneDeep(data));
|
|
105
|
+
/* eslint-enable no-console */
|
|
106
|
+
}
|
|
107
|
+
globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {
|
|
108
|
+
...state,
|
|
109
|
+
data,
|
|
110
|
+
operationId: '',
|
|
111
|
+
timestamp: Date.now(),
|
|
112
|
+
});
|
|
113
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
114
|
+
/* eslint-disable no-console */
|
|
115
|
+
console.groupEnd();
|
|
116
|
+
/* eslint-enable no-console */
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Resolves asynchronous data, and stores them at given `path` of global
|
|
123
|
+
* state. When multiple components rely on asynchronous data at the same `path`,
|
|
124
|
+
* the data are resolved once, and reused until their age is within specified
|
|
125
|
+
* bounds. Once the data are stale, the hook allows to refresh them. It also
|
|
126
|
+
* garbage-collects stale data from the global state when the last component
|
|
127
|
+
* relying on them is unmounted.
|
|
128
|
+
* @param path Dot-delimitered state path, where data envelop is
|
|
129
|
+
* stored.
|
|
130
|
+
* @param loader Asynchronous function which resolves (loads)
|
|
131
|
+
* data, which should be stored at the global state `path`. When multiple
|
|
132
|
+
* components
|
|
133
|
+
* use `useAsyncData()` hook for the same `path`, the library assumes that all
|
|
134
|
+
* hook instances are called with the same `loader` (_i.e._ whichever of these
|
|
135
|
+
* loaders is used to resolve async data, the result is acceptable to be reused
|
|
136
|
+
* in all related components).
|
|
137
|
+
* @param options Additional options.
|
|
138
|
+
* @param options.deps An array of dependencies, which trigger
|
|
139
|
+
* data reload when changed. Given dependency changes are watched shallowly
|
|
140
|
+
* (similarly to the standard React's
|
|
141
|
+
* [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
|
|
142
|
+
* @param options.noSSR If `true`, this hook won't load data during
|
|
143
|
+
* server-side rendering.
|
|
144
|
+
* @param options.garbageCollectAge The maximum age of data
|
|
145
|
+
* (in milliseconds), after which they are dropped from the state when the last
|
|
146
|
+
* component referencing them via `useAsyncData()` hook unmounts. Defaults to
|
|
147
|
+
* `maxage` option value.
|
|
148
|
+
* @param options.maxage The maximum age of
|
|
149
|
+
* data (in milliseconds) acceptable to the hook's caller. If loaded data are
|
|
150
|
+
* older than this value, `null` is returned instead. Defaults to 5 minutes.
|
|
151
|
+
* @param options.refreshAge The maximum age of data
|
|
152
|
+
* (in milliseconds), after which their refreshment will be triggered when
|
|
153
|
+
* any component referencing them via `useAsyncData()` hook (re-)renders.
|
|
154
|
+
* Defaults to `maxage` value.
|
|
155
|
+
* @return Returns an object with three fields: `data` holds the actual result of
|
|
156
|
+
* last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
|
|
157
|
+
* is a boolean flag, which is `true` if data are being loaded (the hook is
|
|
158
|
+
* waiting for `loader` function resolution); `timestamp` (in milliseconds)
|
|
159
|
+
* is Unix timestamp of related data currently loaded into the global state.
|
|
160
|
+
*
|
|
161
|
+
* Note that loaded data, if any, are stored at the given `path` of global state
|
|
162
|
+
* along with related meta-information, using slightly different state segment
|
|
163
|
+
* structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
|
|
164
|
+
* can be accessed, and even modified using other hooks,
|
|
165
|
+
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
166
|
+
* `useAsyncData()` hooks logic.
|
|
167
|
+
*/
|
|
168
|
+
|
|
169
|
+
export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>
|
|
170
|
+
= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>
|
|
171
|
+
? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>
|
|
172
|
+
: void;
|
|
173
|
+
|
|
174
|
+
function useAsyncData<
|
|
175
|
+
StateT,
|
|
176
|
+
PathT extends null | string | undefined,
|
|
177
|
+
>(
|
|
178
|
+
path: PathT,
|
|
179
|
+
loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,
|
|
180
|
+
options?: UseAsyncDataOptionsT,
|
|
181
|
+
): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
182
|
+
|
|
183
|
+
function useAsyncData<
|
|
184
|
+
Forced extends ForceT | false = false,
|
|
185
|
+
DataT = unknown,
|
|
186
|
+
>(
|
|
187
|
+
path: null | string | undefined,
|
|
188
|
+
loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,
|
|
189
|
+
options?: UseAsyncDataOptionsT,
|
|
190
|
+
): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
191
|
+
|
|
192
|
+
function useAsyncData<DataT>(
|
|
193
|
+
path: null | string | undefined,
|
|
194
|
+
loader: AsyncDataLoaderT<DataT>,
|
|
195
|
+
options: UseAsyncDataOptionsT = {},
|
|
196
|
+
): UseAsyncDataResT<DataT> {
|
|
197
|
+
const maxage: number = options.maxage === undefined
|
|
198
|
+
? DEFAULT_MAXAGE : options.maxage;
|
|
199
|
+
|
|
200
|
+
const refreshAge: number = options.refreshAge === undefined
|
|
201
|
+
? maxage : options.refreshAge;
|
|
202
|
+
|
|
203
|
+
const garbageCollectAge: number = options.garbageCollectAge === undefined
|
|
204
|
+
? maxage : options.garbageCollectAge;
|
|
205
|
+
|
|
206
|
+
// Note: here we can't depend on useGlobalState() to init the initial value,
|
|
207
|
+
// because that way we'll have issues with SSR (see details below).
|
|
208
|
+
const globalState = getGlobalState();
|
|
209
|
+
const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {
|
|
210
|
+
initialValue: newAsyncDataEnvelope<DataT>(),
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
if (globalState.ssrContext && !options.noSSR) {
|
|
214
|
+
if (!state.timestamp && !state.operationId) {
|
|
215
|
+
globalState.ssrContext.pending.push(
|
|
216
|
+
load(path, loader, globalState, state.data, 'S'),
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
} else {
|
|
220
|
+
// This takes care about the client-side reference counting, and garbage
|
|
221
|
+
// collection.
|
|
222
|
+
//
|
|
223
|
+
// Note: the Rules of Hook below are violated by conditional call to a hook,
|
|
224
|
+
// but as the condition is actually server-side or client-side environment,
|
|
225
|
+
// it is effectively non-conditional at the runtime.
|
|
226
|
+
//
|
|
227
|
+
// TODO: Though, maybe there is a way to refactor it into a cleaner code.
|
|
228
|
+
// The same applies to other useEffect() hooks below.
|
|
229
|
+
useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
|
|
230
|
+
const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
|
|
231
|
+
const numRefs = globalState.get<ForceT, number>(numRefsPath);
|
|
232
|
+
globalState.set<ForceT, number>(numRefsPath, numRefs + 1);
|
|
233
|
+
return () => {
|
|
234
|
+
const state2: AsyncDataEnvelopeT<DataT> = globalState.get<
|
|
235
|
+
ForceT, AsyncDataEnvelopeT<DataT>>(
|
|
236
|
+
path,
|
|
237
|
+
);
|
|
238
|
+
if (
|
|
239
|
+
state2.numRefs === 1
|
|
240
|
+
&& garbageCollectAge < Date.now() - state2.timestamp
|
|
241
|
+
) {
|
|
242
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
243
|
+
/* eslint-disable no-console */
|
|
244
|
+
console.log(
|
|
245
|
+
`ReactGlobalState - useAsyncData garbage collected at path ${
|
|
246
|
+
path || ''
|
|
247
|
+
}`,
|
|
248
|
+
);
|
|
249
|
+
/* eslint-enable no-console */
|
|
250
|
+
}
|
|
251
|
+
globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {
|
|
252
|
+
...state2,
|
|
253
|
+
data: null,
|
|
254
|
+
numRefs: 0,
|
|
255
|
+
timestamp: 0,
|
|
256
|
+
});
|
|
257
|
+
} else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);
|
|
258
|
+
};
|
|
259
|
+
}, [garbageCollectAge, globalState, path]);
|
|
260
|
+
|
|
261
|
+
// Note: a bunch of Rules of Hooks ignored belows because in our very
|
|
262
|
+
// special case the otherwise wrong behavior is actually what we need.
|
|
263
|
+
|
|
264
|
+
// Data loading and refreshing.
|
|
265
|
+
let loadTriggered = false;
|
|
266
|
+
useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
|
|
267
|
+
const state2: AsyncDataEnvelopeT<DataT> = globalState.get<
|
|
268
|
+
ForceT, AsyncDataEnvelopeT<DataT>>(path);
|
|
269
|
+
|
|
270
|
+
if (refreshAge < Date.now() - state2.timestamp
|
|
271
|
+
&& (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
|
|
272
|
+
load(path, loader, globalState, state2.data);
|
|
273
|
+
loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
const deps = options.deps || [];
|
|
278
|
+
useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
|
|
279
|
+
if (!loadTriggered && deps.length) load(path, loader, globalState, null);
|
|
280
|
+
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(
|
|
284
|
+
path,
|
|
285
|
+
newAsyncDataEnvelope<DataT>(),
|
|
286
|
+
);
|
|
287
|
+
|
|
288
|
+
return {
|
|
289
|
+
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
290
|
+
loading: Boolean(localState.operationId),
|
|
291
|
+
timestamp: localState.timestamp,
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export default useAsyncData;
|