@dr.pogodin/react-global-state 0.15.1 → 0.16.0

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.
@@ -1,56 +1,219 @@
1
1
  /**
2
- * Loads and uses an item in an async collection.
2
+ * Loads and uses item(s) in an async collection.
3
3
  */
4
4
 
5
- import { useAsyncData } from "./useAsyncData";
5
+ import { useEffect, useRef } from 'react';
6
+ import { v4 as uuid } from 'uuid';
7
+ import { getGlobalState } from "./GlobalStateProvider";
8
+ import { DEFAULT_MAXAGE, load, newAsyncDataEnvelope } from "./useAsyncData";
9
+ import useGlobalState from "./useGlobalState";
10
+ import { isDebugMode } from "./utils";
6
11
 
7
12
  /**
8
- * Resolves and stores at the given `path` of global state elements of
9
- * an asynchronous data collection. In other words, it is an auxiliar wrapper
10
- * around {@link useAsyncData}, which uses a loader which resolves to different
11
- * data, based on ID argument passed in, and stores data fetched for different
12
- * IDs in the state.
13
- * @param id ID of the collection item to load & use.
14
- * @param path The global state path where entire collection should be
15
- * stored.
16
- * @param loader A loader function, which takes an
17
- * ID of data to load, and resolves to the corresponding data.
18
- * @param options Additional options.
19
- * @param options.deps An array of dependencies, which trigger
20
- * data reload when changed. Given dependency changes are watched shallowly
21
- * (similarly to the standard React's
22
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
23
- * @param options.noSSR If `true`, this hook won't load data during
24
- * server-side rendering.
25
- * @param options.garbageCollectAge The maximum age of data
26
- * (in milliseconds), after which they are dropped from the state when the last
27
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
28
- * `maxage` option value.
29
- * @param options.maxage The maximum age of
30
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
31
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
32
- * @param options.refreshAge The maximum age of data
33
- * (in milliseconds), after which their refreshment will be triggered when
34
- * any component referencing them via `useAsyncData()` hook (re-)renders.
35
- * Defaults to `maxage` value.
36
- * @return Returns an object with three fields: `data` holds the actual result of
37
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
38
- * is a boolean flag, which is `true` if data are being loaded (the hook is
39
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
40
- * is Unix timestamp of related data currently loaded into the global state.
41
- *
42
- * Note that loaded data, if any, are stored at the given `path` of global state
43
- * along with related meta-information, using slightly different state segment
44
- * structure (see {@link AsyncDataEnvelope}). That segment of the global state
45
- * can be accessed, and even modified using other hooks,
46
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
47
- * `useAsyncData()` hooks logic.
13
+ * Resolves and stores at the given `path` of the global state elements of
14
+ * an asynchronous data collection.
48
15
  */
49
16
 
50
- function useAsyncCollection(id, path, loader) {
17
+ // TODO: This is largely similar to useAsyncData() logic, just more generic.
18
+ // Perhaps, a bunch of logic blocks can be split into stand-alone functions,
19
+ // and reused in both hooks.
20
+ function useAsyncCollection(idOrIds, path, loader) {
21
+ var _options$maxage, _options$refreshAge, _options$garbageColle;
51
22
  let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
52
- const itemPath = path ? `${path}.${id}` : id;
53
- return useAsyncData(itemPath, oldData => loader(id, oldData), options);
23
+ const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
24
+ const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
25
+ const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
26
+ const garbageCollectAge = (_options$garbageColle = options.garbageCollectAge) !== null && _options$garbageColle !== void 0 ? _options$garbageColle : maxage;
27
+
28
+ // To avoid unnecessary work if consumer passes down the same IDs
29
+ // in an unstable order.
30
+ // TODO: Should we also filter out any duplicates? Or just assume consumer
31
+ // knows what he is doing, and won't place duplicates into IDs array?e
32
+ ids.sort();
33
+ const globalState = getGlobalState();
34
+ const {
35
+ current: heap
36
+ } = useRef({});
37
+ heap.globalState = globalState;
38
+ heap.ids = ids;
39
+ heap.path = path;
40
+ heap.loader = loader;
41
+ if (!heap.reload) {
42
+ heap.reload = async customLoader => {
43
+ const localLoader = customLoader || heap.loader;
44
+ if (!localLoader || !heap.globalState || !heap.ids) {
45
+ throw Error('Internal error');
46
+ }
47
+ for (let i = 0; i < heap.ids.length; ++i) {
48
+ const id = heap.ids[i];
49
+ const itemPath = heap.path ? `${heap.path}.${id}` : `${id}`;
50
+
51
+ // eslint-disable-next-line no-await-in-loop
52
+ await load(itemPath, (oldData, meta) => localLoader(id, oldData, meta), heap.globalState);
53
+ }
54
+ };
55
+ }
56
+ if (!Array.isArray(idOrIds)) {
57
+ heap.reloadD = customLoader => heap.reload(customLoader && function (id) {
58
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
59
+ args[_key - 1] = arguments[_key];
60
+ }
61
+ return customLoader(...args);
62
+ });
63
+ }
64
+
65
+ // Server-side logic.
66
+ if (globalState.ssrContext && !options.noSSR) {
67
+ const operationId = `S${uuid()}`;
68
+ for (let i = 0; i < ids.length; ++i) {
69
+ const id = ids[i];
70
+ const itemPath = path ? `${path}.${id}` : `${id}`;
71
+ const state = globalState.get(itemPath, {
72
+ initialValue: newAsyncDataEnvelope()
73
+ });
74
+ if (!state.timestamp && !state.operationId) {
75
+ globalState.ssrContext.pending.push(load(itemPath, function () {
76
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
77
+ args[_key2] = arguments[_key2];
78
+ }
79
+ return loader(id, ...args);
80
+ }, globalState, {
81
+ data: state.data,
82
+ timestamp: state.timestamp
83
+ }, operationId));
84
+ }
85
+ }
86
+
87
+ // Client-side logic.
88
+ } else {
89
+ // Reference-counting & garbage collection.
90
+
91
+ // TODO: Violation of rules of hooks is fine here,
92
+ // but perhaps it can be refactored to avoid the need for it.
93
+ useEffect(() => {
94
+ // eslint-disable-line react-hooks/rules-of-hooks
95
+ for (let i = 0; i < ids.length; ++i) {
96
+ const id = ids[i];
97
+ const itemPath = path ? `${path}.${id}` : `${id}`;
98
+ const state = globalState.get(itemPath, {
99
+ initialValue: newAsyncDataEnvelope()
100
+ });
101
+ const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
102
+ globalState.set(numRefsPath, state.numRefs + 1);
103
+ }
104
+ return () => {
105
+ for (let i = 0; i < ids.length; ++i) {
106
+ const id = ids[i];
107
+ const itemPath = path ? `${path}.${id}` : `${id}`;
108
+ const state2 = globalState.get(itemPath);
109
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
110
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
111
+ /* eslint-disable no-console */
112
+ console.log(`ReactGlobalState - useAsyncCollection garbage collected at path ${itemPath || ''}`);
113
+ /* eslint-enable no-console */
114
+ }
115
+ globalState.dropDependencies(itemPath || '');
116
+ globalState.set(itemPath, {
117
+ ...state2,
118
+ data: null,
119
+ numRefs: 0,
120
+ timestamp: 0
121
+ });
122
+ } else {
123
+ const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
124
+ globalState.set(numRefsPath, state2.numRefs - 1);
125
+ }
126
+ }
127
+ };
128
+ // eslint-disable-next-line react-hooks/exhaustive-deps
129
+ }, [garbageCollectAge, globalState, path, ...ids]);
130
+
131
+ // NOTE: a bunch of Rules of Hooks ignored belows because in our very
132
+ // special case the otherwise wrong behavior is actually what we need.
133
+
134
+ // Data loading and refreshing.
135
+ const loadTriggeredForIds = new Set();
136
+ useEffect(() => {
137
+ // eslint-disable-line react-hooks/rules-of-hooks
138
+ (async () => {
139
+ for (let i = 0; i < ids.length; ++i) {
140
+ const id = ids[i];
141
+ const itemPath = path ? `${path}.${id}` : `${id}`;
142
+ const state2 = globalState.get(itemPath);
143
+ const {
144
+ deps
145
+ } = options;
146
+ if (deps && globalState.hasChangedDependencies(itemPath, deps) || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
147
+ if (!deps) globalState.dropDependencies(itemPath);
148
+ loadTriggeredForIds.add(id);
149
+ // eslint-disable-next-line no-await-in-loop
150
+ await load(itemPath, function () {
151
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
152
+ args[_key3] = arguments[_key3];
153
+ }
154
+ return loader(id, ...args);
155
+ }, globalState, {
156
+ data: state2.data,
157
+ timestamp: state2.timestamp
158
+ });
159
+ }
160
+ }
161
+ })();
162
+ });
163
+ useEffect(() => {
164
+ // eslint-disable-line react-hooks/rules-of-hooks
165
+ (async () => {
166
+ const {
167
+ deps
168
+ } = options;
169
+ for (let i = 0; i < ids.length; ++i) {
170
+ const id = ids[i];
171
+ const itemPath = path ? `${path}.${id}` : `${id}`;
172
+ if (deps && globalState.hasChangedDependencies(itemPath || '', deps) && !loadTriggeredForIds.has(id)) {
173
+ // eslint-disable-next-line no-await-in-loop
174
+ await load(itemPath, (oldData, meta) => loader(id, oldData, meta), globalState);
175
+ }
176
+ }
177
+ })();
178
+
179
+ // Here we need to default to empty array, so that this hook is re-evaluated
180
+ // only when dependencies specified in options change, and it should not be
181
+ // re-evaluated at all if no `deps` option is used.
182
+ }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps
183
+ }
184
+ const [localState] = useGlobalState(path, {});
185
+ if (!Array.isArray(idOrIds)) {
186
+ var _e$timestamp, _e$data;
187
+ const e = localState[idOrIds];
188
+ const timestamp = (_e$timestamp = e === null || e === void 0 ? void 0 : e.timestamp) !== null && _e$timestamp !== void 0 ? _e$timestamp : 0;
189
+ return {
190
+ data: maxage < Date.now() - timestamp ? null : (_e$data = e === null || e === void 0 ? void 0 : e.data) !== null && _e$data !== void 0 ? _e$data : null,
191
+ loading: !!(e !== null && e !== void 0 && e.operationId),
192
+ reload: heap.reloadD,
193
+ timestamp
194
+ };
195
+ }
196
+ const res = {
197
+ items: {},
198
+ loading: false,
199
+ reload: heap.reload,
200
+ timestamp: Number.MAX_VALUE
201
+ };
202
+ for (let i = 0; i < ids.length; ++i) {
203
+ var _e$timestamp2, _e$data2;
204
+ const id = ids[i];
205
+ const e = localState[id];
206
+ const loading = !!(e !== null && e !== void 0 && e.operationId);
207
+ const timestamp = (_e$timestamp2 = e === null || e === void 0 ? void 0 : e.timestamp) !== null && _e$timestamp2 !== void 0 ? _e$timestamp2 : 0;
208
+ res.items[id] = {
209
+ data: maxage < Date.now() - timestamp ? null : (_e$data2 = e === null || e === void 0 ? void 0 : e.data) !== null && _e$data2 !== void 0 ? _e$data2 : null,
210
+ loading,
211
+ timestamp
212
+ };
213
+ res.loading || (res.loading = loading);
214
+ if (res.timestamp > timestamp) res.timestamp = timestamp;
215
+ }
216
+ return res;
54
217
  }
55
218
  export default useAsyncCollection;
56
219
  //# sourceMappingURL=useAsyncCollection.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["useAsyncData","useAsyncCollection","id","path","loader","options","arguments","length","undefined","itemPath","oldData"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n useAsyncData,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\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 id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param 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 options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge 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 options.maxage 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 options.refreshAge 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 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 */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAIEA,YAAY;;AAQd;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;;AA0BA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EAEZ;EAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAElC,MAAMG,QAAQ,GAAGN,IAAI,GAAG,GAAGA,IAAI,IAAID,EAAE,EAAE,GAAGA,EAAE;EAC5C,OAAOF,YAAY,CACjBS,QAAQ,EACPC,OAAqB,IAAKN,MAAM,CAACF,EAAE,EAAEQ,OAAO,CAAC,EAC9CL,OACF,CAAC;AACH;AAEA,eAAeJ,kBAAkB","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","isDebugMode","useAsyncCollection","idOrIds","path","loader","_options$maxage","_options$refreshAge","_options$garbageColle","options","arguments","length","undefined","ids","Array","isArray","maxage","refreshAge","garbageCollectAge","sort","globalState","current","heap","reload","customLoader","localLoader","Error","i","id","itemPath","oldData","meta","reloadD","_len","args","_key","ssrContext","noSSR","operationId","state","get","initialValue","timestamp","pending","push","_len2","_key2","data","numRefsPath","set","numRefs","state2","Date","now","process","env","NODE_ENV","console","log","dropDependencies","loadTriggeredForIds","Set","deps","hasChangedDependencies","charAt","add","_len3","_key3","has","localState","_e$timestamp","_e$data","e","loading","res","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> =\n (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: {\n [id in IdT]: CollectionItemT<DataT>;\n }\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype HeapT<\n DataT,\n IdT extends number | string,\n> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n ids?: IdT[];\n path?: null | string;\n loader?: AsyncCollectionLoaderT<DataT, IdT>;\n reload?: AsyncCollectionReloaderT<DataT, IdT>;\n reloadD?: AsyncDataReloaderT<DataT>;\n};\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // To avoid unnecessary work if consumer passes down the same IDs\n // in an unstable order.\n // TODO: Should we also filter out any duplicates? Or just assume consumer\n // knows what he is doing, and won't place duplicates into IDs array?e\n ids.sort();\n\n const globalState = getGlobalState();\n\n const { current: heap } = useRef<HeapT<DataT, IdT>>({});\n\n heap.globalState = globalState;\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = async (customLoader?: AsyncCollectionLoaderT<DataT, IdT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState || !heap.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap.ids.length; ++i) {\n const id = heap.ids[i]!;\n const itemPath = heap.path ? `${heap.path}.${id}` : `${id}`;\n\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap.globalState,\n );\n }\n };\n }\n\n if (!Array.isArray(idOrIds)) {\n heap.reloadD = (customLoader) => heap.reload!(\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n }\n\n // Server-side logic.\n if (globalState.ssrContext && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\n );\n }\n }\n\n // Client-side logic.\n } else {\n // Reference-counting & garbage collection.\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i];\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n { initialValue: newAsyncDataEnvelope() },\n );\n\n const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';\n globalState.set<ForceT, number>(numRefsPath, state.numRefs + 1);\n }\n\n return () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i];\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>\n >(itemPath);\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 - useAsyncCollection garbage collected at path ${\n itemPath || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(itemPath || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [garbageCollectAge, globalState, path, ...ids]);\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 const loadTriggeredForIds = new Set<IdT>();\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n (async () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n loadTriggeredForIds.add(id);\n // eslint-disable-next-line no-await-in-loop\n await load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n })();\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n (async () => {\n const { deps } = options;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n if (\n deps\n && globalState.hasChangedDependencies(itemPath || '', deps)\n && !loadTriggeredForIds.has(id)\n ) {\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: null | DataT, meta) => loader(id, oldData, meta),\n globalState,\n );\n }\n }\n })();\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<\n ForceT, { [id: string]: AsyncDataEnvelopeT<DataT> }\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n const e = localState[idOrIds];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading: !!e?.operationId,\n reload: heap.reloadD!,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: heap.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const e = localState[id];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLo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CAAE;IAClB,MAAM6C,CAAC,GAAGH,UAAU,CAACzC,EAAE,CAAC;IACxB,MAAM6C,OAAO,GAAG,CAAC,EAACD,CAAC,aAADA,CAAC,eAADA,CAAC,CAAElC,WAAW;IAChC,MAAMI,SAAS,IAAAoC,aAAA,GAAGN,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAE9B,SAAS,cAAAoC,aAAA,cAAAA,aAAA,GAAI,CAAC;IAEnCJ,GAAG,CAACC,KAAK,CAAC/C,EAAE,CAAC,GAAG;MACdmB,IAAI,EAAE/B,MAAM,GAAGoC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGX,SAAS,GAAG,IAAI,IAAAqC,QAAA,GAAIP,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAEzB,IAAI,cAAAgC,QAAA,cAAAA,QAAA,GAAI,IAAK;MAChEN,OAAO;MACP/B;IACF,CAAC;IACDgC,GAAG,CAACD,OAAO,KAAXC,GAAG,CAACD,OAAO,GAAKA,OAAO;IACvB,IAAIC,GAAG,CAAChC,SAAS,GAAGA,SAAS,EAAEgC,GAAG,CAAChC,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOgC,GAAG;AACZ;AAEA,eAAexE,kBAAkB","ignoreList":[]}
@@ -8,7 +8,7 @@ import { MIN_MS } from '@dr.pogodin/js-utils';
8
8
  import { getGlobalState } from "./GlobalStateProvider";
9
9
  import useGlobalState from "./useGlobalState";
10
10
  import { cloneDeepForLog, isDebugMode } from "./utils";
11
- const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
11
+ export const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
12
12
 
13
13
  export function newAsyncDataEnvelope() {
14
14
  let initialData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
@@ -37,23 +37,38 @@ export function newAsyncDataEnvelope() {
37
37
  * @return Resolves once the operation is done.
38
38
  * @ignore
39
39
  */
40
- async function load(path, loader, globalState, oldData) {
41
- let opIdPrefix = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'C';
40
+ export async function load(path, loader, globalState, old) {
41
+ let operationId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : `C${uuid()}`;
42
42
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
43
43
  /* eslint-disable no-console */
44
- console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
44
+ console.log(`ReactGlobalState: async data (re-)loading. Path: "${path || ''}"`);
45
45
  /* eslint-enable no-console */
46
46
  }
47
- const operationId = opIdPrefix + uuid();
48
47
  const operationIdPath = path ? `${path}.operationId` : 'operationId';
49
48
  globalState.set(operationIdPath, operationId);
50
- const dataOrLoader = loader(oldData || globalState.get(path).data);
51
- const data = dataOrLoader instanceof Promise ? await dataOrLoader : dataOrLoader;
49
+ let definedOld = old;
50
+ if (!definedOld) {
51
+ // TODO: Can we improve the typing, to avoid ForceT?
52
+ const e = globalState.get(path);
53
+ definedOld = {
54
+ data: e.data,
55
+ timestamp: e.timestamp
56
+ };
57
+ }
58
+ const dataOrPromise = loader(definedOld.data, {
59
+ isAborted: () => {
60
+ // TODO: Can we improve the typing, to avoid ForceT?
61
+ const opid = globalState.get(path).operationId;
62
+ return opid !== operationId;
63
+ },
64
+ oldDataTimestamp: definedOld.timestamp
65
+ });
66
+ const data = dataOrPromise instanceof Promise ? await dataOrPromise : dataOrPromise;
52
67
  const state = globalState.get(path);
53
68
  if (operationId === state.operationId) {
54
69
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
55
70
  /* eslint-disable no-console */
56
- console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
71
+ console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path || ''}"`);
57
72
  console.log('Data:', cloneDeepForLog(data, path !== null && path !== void 0 ? path : ''));
58
73
  /* eslint-enable no-console */
59
74
  }
@@ -73,57 +88,15 @@ async function load(path, loader, globalState, oldData) {
73
88
 
74
89
  /**
75
90
  * Resolves asynchronous data, and stores them at given `path` of global
76
- * state. When multiple components rely on asynchronous data at the same `path`,
77
- * the data are resolved once, and reused until their age is within specified
78
- * bounds. Once the data are stale, the hook allows to refresh them. It also
79
- * garbage-collects stale data from the global state when the last component
80
- * relying on them is unmounted.
81
- * @param path Dot-delimitered state path, where data envelop is
82
- * stored.
83
- * @param loader Asynchronous function which resolves (loads)
84
- * data, which should be stored at the global state `path`. When multiple
85
- * components
86
- * use `useAsyncData()` hook for the same `path`, the library assumes that all
87
- * hook instances are called with the same `loader` (_i.e._ whichever of these
88
- * loaders is used to resolve async data, the result is acceptable to be reused
89
- * in all related components).
90
- * @param options Additional options.
91
- * @param options.deps An array of dependencies, which trigger
92
- * data reload when changed. Given dependency changes are watched shallowly
93
- * (similarly to the standard React's
94
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
95
- * @param options.noSSR If `true`, this hook won't load data during
96
- * server-side rendering.
97
- * @param options.garbageCollectAge The maximum age of data
98
- * (in milliseconds), after which they are dropped from the state when the last
99
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
100
- * `maxage` option value.
101
- * @param options.maxage The maximum age of
102
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
103
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
104
- * @param options.refreshAge The maximum age of data
105
- * (in milliseconds), after which their refreshment will be triggered when
106
- * any component referencing them via `useAsyncData()` hook (re-)renders.
107
- * Defaults to `maxage` value.
108
- * @return Returns an object with three fields: `data` holds the actual result of
109
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
110
- * is a boolean flag, which is `true` if data are being loaded (the hook is
111
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
112
- * is Unix timestamp of related data currently loaded into the global state.
113
- *
114
- * Note that loaded data, if any, are stored at the given `path` of global state
115
- * along with related meta-information, using slightly different state segment
116
- * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
117
- * can be accessed, and even modified using other hooks,
118
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
119
- * `useAsyncData()` hooks logic.
91
+ * state.
120
92
  */
121
93
 
122
94
  function useAsyncData(path, loader) {
95
+ var _options$maxage, _options$refreshAge, _options$garbageColle;
123
96
  let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
124
- const maxage = options.maxage === undefined ? DEFAULT_MAXAGE : options.maxage;
125
- const refreshAge = options.refreshAge === undefined ? maxage : options.refreshAge;
126
- const garbageCollectAge = options.garbageCollectAge === undefined ? maxage : options.garbageCollectAge;
97
+ const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
98
+ const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
99
+ const garbageCollectAge = (_options$garbageColle = options.garbageCollectAge) !== null && _options$garbageColle !== void 0 ? _options$garbageColle : maxage;
127
100
 
128
101
  // Note: here we can't depend on useGlobalState() to init the initial value,
129
102
  // because that way we'll have issues with SSR (see details below).
@@ -141,12 +114,15 @@ function useAsyncData(path, loader) {
141
114
  heap.reload = customLoader => {
142
115
  const localLoader = customLoader || heap.loader;
143
116
  if (!localLoader || !heap.globalState) throw Error('Internal error');
144
- return load(heap.path, localLoader, heap.globalState, null);
117
+ return load(heap.path, localLoader, heap.globalState);
145
118
  };
146
119
  }
147
120
  if (globalState.ssrContext && !options.noSSR) {
148
121
  if (!state.timestamp && !state.operationId) {
149
- globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
122
+ globalState.ssrContext.pending.push(load(path, loader, globalState, {
123
+ data: state.data,
124
+ timestamp: state.timestamp
125
+ }, `S${uuid()}`));
150
126
  }
151
127
  } else {
152
128
  // This takes care about the client-side reference counting, and garbage
@@ -190,9 +166,22 @@ function useAsyncData(path, loader) {
190
166
  useEffect(() => {
191
167
  // eslint-disable-line react-hooks/rules-of-hooks
192
168
  const state2 = globalState.get(path);
193
- if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
194
- load(path, loader, globalState, state2.data);
169
+ const {
170
+ deps
171
+ } = options;
172
+ if (
173
+ // The hook is called with a list of dependencies, that mismatch
174
+ // dependencies last used to retrieve the data at given path.
175
+ deps && globalState.hasChangedDependencies(path || '', deps)
176
+
177
+ // Data at the path are stale, and are not being loaded.
178
+ || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
195
179
  loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
180
+ if (!deps) globalState.dropDependencies(path || '');
181
+ load(path, loader, globalState, {
182
+ data: state2.data,
183
+ timestamp: state2.timestamp
184
+ });
196
185
  }
197
186
  });
198
187
  useEffect(() => {
@@ -201,7 +190,7 @@ function useAsyncData(path, loader) {
201
190
  deps
202
191
  } = options;
203
192
  if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {
204
- load(path, loader, globalState, null);
193
+ load(path, loader, globalState);
205
194
  }
206
195
 
207
196
  // Here we need to default to empty array, so that this hook is re-evaluated
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","numRefs","timestamp","data","operationId","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","dataOrLoader","get","Promise","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","Error","ssrContext","noSSR","pending","push","numRefsPath","state2","dropDependencies","loadTriggered","charAt","deps","hasChangedDependencies","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param 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 opIdPrefix 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 Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\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<ForceT, string>(operationIdPath, operationId);\n\n const dataOrLoader = loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n\n const data: DataT = dataOrLoader instanceof Promise\n ? await dataOrLoader : dataOrLoader;\n\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(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:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(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 path Dot-delimitered state path, where data envelop is\n * stored.\n * @param 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 options Additional options.\n * @param 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 options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge 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 options.maxage 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 options.refreshAge 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 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 AsyncDataEnvelopeT}). 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 */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\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<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState, null);\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<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\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.dropDependencies(path || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(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: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {\n load(path, loader, globalState, null);\n }\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,eAAe,EACfC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGL,MAAM,CAAC,CAAC;;AAenC,OAAO,SAASM,oBAAoBA,CAAA,EAGP;EAAA,IAF3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAAA,IAChC;IAAEG,OAAO,GAAG,CAAC;IAAEC,SAAS,GAAG;EAAE,CAAC,GAAAJ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAEnC,OAAO;IACLK,IAAI,EAAEN,WAAW;IACjBI,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeG,IAAIA,CACjBC,IAA+B,EAC/BC,MAA+B,EAC/BC,WAAsD,EACtDC,OAAqB,EAEN;EAAA,IADfC,UAAqB,GAAAZ,SAAA,CAAAC,MAAA,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AI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;MACvC;;MAEF;MACA;MACA;IACA,CAAC,EAAEmB,OAAO,CAACoB,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;EAC1B;EAEA,MAAM,CAACE,UAAU,CAAC,GAAGzD,cAAc,CACjCc,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLO,IAAI,EAAEyB,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGyB,UAAU,CAAC/C,SAAS,GAAG,IAAI,GAAG+C,UAAU,CAAC9C,IAAI;IACzE+C,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC7C,WAAW,CAAC;IACxC8B,MAAM,EAAED,IAAI,CAACC,MAAM;IACnBhC,SAAS,EAAE+C,UAAU,CAAC/C;EACxB,CAAC;AACH;AAEA,SAASwB,YAAY","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","numRefs","timestamp","data","operationId","load","path","loader","globalState","old","process","env","NODE_ENV","console","log","operationIdPath","set","definedOld","e","get","dataOrPromise","isAborted","opid","oldDataTimestamp","Promise","state","groupCollapsed","Date","now","groupEnd","useAsyncData","_options$maxage","_options$refreshAge","_options$garbageColle","options","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","Error","ssrContext","noSSR","pending","push","numRefsPath","state2","dropDependencies","loadTriggered","deps","hasChangedDependencies","charAt","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param 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 opIdPrefix 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 Resolves once the operation is done.\n * @ignore\n */\nexport async function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null, timestamp: number },\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n });\n\n const data: DataT | null = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\n\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(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.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.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<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\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, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\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<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\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.dropDependencies(path || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(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: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path || '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n if (!deps) globalState.dropDependencies(path || '');\n load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (\n deps\n && globalState.hasChangedDependencies(path || '', deps)\n && !loadTriggered\n ) {\n load(path, loader, globalState);\n }\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,eAAe,EACfC,WAAW;AAMb,OAAO,MAAMC,cAAc,GAAG,CAAC,GAAGL,MAAM,CAAC,CAAC;;AAoB1C,OAAO,SAASM,oBAAoBA,CAAA,EAGP;EAAA,IAF3BC,WAAyB,GAAAC,SAAA,CAAAC,MA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IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;EAC1B;EAEA,MAAM,CAACG,UAAU,CAAC,GAAGhE,cAAc,CACjCc,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLO,IAAI,EAAEgC,MAAM,GAAGR,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG4B,UAAU,CAACtD,SAAS,GAAG,IAAI,GAAGsD,UAAU,CAACrD,IAAI;IACzEsD,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACpD,WAAW,CAAC;IACxCqC,MAAM,EAAED,IAAI,CAACC,MAAM;IACnBvC,SAAS,EAAEsD,UAAU,CAACtD;EACxB,CAAC;AACH;AAEA,SAAS4B,YAAY","ignoreList":[]}
@@ -1,14 +1,13 @@
1
1
  import GlobalState from './GlobalState';
2
2
  import GlobalStateProvider, { getGlobalState, getSsrContext } from './GlobalStateProvider';
3
3
  import SsrContext from './SsrContext';
4
- import useAsyncCollection, { type UseAsyncCollectionI } from './useAsyncCollection';
5
- import { type UseAsyncDataI, newAsyncDataEnvelope } from './useAsyncData';
4
+ import useAsyncCollection, { type UseAsyncCollectionI, type UseAsyncCollectionResT } from './useAsyncCollection';
5
+ import { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, type UseAsyncDataI, type UseAsyncDataResT, newAsyncDataEnvelope, useAsyncData } from './useAsyncData';
6
6
  import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
7
7
  export type { AsyncCollectionLoaderT } from './useAsyncCollection';
8
- export * from './useAsyncData';
9
8
  export type { SetterT, UseGlobalStateResT } from './useGlobalState';
10
9
  export type { ForceT, ValueOrInitializerT } from './utils';
11
- export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, SsrContext, useAsyncCollection, useGlobalState, };
10
+ export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, type UseAsyncCollectionResT, type UseAsyncDataResT, getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState, };
12
11
  interface API<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>> {
13
12
  getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
14
13
  getSsrContext: typeof getSsrContext<SsrContextT>;