@dr.pogodin/react-global-state 0.23.0 → 0.25.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.
- package/LICENSE.md +1 -1
- package/build/{code → logic}/GlobalState.js +43 -52
- package/build/logic/GlobalState.js.map +1 -0
- package/build/logic/GlobalStateProvider.js +102 -0
- package/build/logic/GlobalStateProvider.js.map +1 -0
- package/build/logic/SsrContext.js +8 -0
- package/build/logic/SsrContext.js.map +1 -0
- package/build/{code → logic}/index.js +5 -5
- package/build/logic/index.js.map +1 -0
- package/build/{code → logic}/useAsyncCollection.js +88 -83
- package/build/logic/useAsyncCollection.js.map +1 -0
- package/build/{code → logic}/useAsyncData.js +175 -79
- package/build/logic/useAsyncData.js.map +1 -0
- package/build/{code → logic}/useGlobalState.js +8 -10
- package/build/logic/useGlobalState.js.map +1 -0
- package/build/{code → logic}/utils.js +8 -19
- package/build/logic/utils.js.map +1 -0
- package/build/types/GlobalStateProvider.d.ts +14 -16
- package/build/types/index.d.ts +4 -4
- package/build/types/utils.d.ts +2 -14
- package/package.json +29 -26
- package/build/code/GlobalState.js.map +0 -1
- package/build/code/GlobalStateProvider.js +0 -90
- package/build/code/GlobalStateProvider.js.map +0 -1
- package/build/code/SsrContext.js +0 -9
- package/build/code/SsrContext.js.map +0 -1
- package/build/code/index.js.map +0 -1
- package/build/code/useAsyncCollection.js.map +0 -1
- package/build/code/useAsyncData.js.map +0 -1
- package/build/code/useGlobalState.js.map +0 -1
- package/build/code/utils.js.map +0 -1
- package/eslint.config.mjs +0 -19
- package/tsconfig.json +0 -21
- package/tsconfig.types.json +0 -14
- package/tstyche.json +0 -6
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { useEffect, useRef, useState } from 'react';
|
|
6
|
-
import {
|
|
6
|
+
import { useGlobalStateObject } from "./GlobalStateProvider.js";
|
|
7
7
|
import { DEFAULT_MAXAGE, loadAsyncData, newAsyncDataEnvelope } from "./useAsyncData.js";
|
|
8
8
|
import useGlobalState from "./useGlobalState.js";
|
|
9
|
-
import {
|
|
9
|
+
import { areEqual, isDebugMode } from "./utils.js";
|
|
10
10
|
/**
|
|
11
11
|
* GarbageCollector: the piece of logic executed on mounting of
|
|
12
12
|
* an useAsyncCollection() hook, and on update of hook params, to update
|
|
@@ -91,12 +91,11 @@ function normalizeIds(idOrIds) {
|
|
|
91
91
|
// and reused in both hooks.
|
|
92
92
|
// eslint-disable-next-line complexity
|
|
93
93
|
function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
94
|
-
var _options$maxage, _options$refreshAge, _options$garbageColle, _ref$current;
|
|
95
94
|
const ids = normalizeIds(idOrIds);
|
|
96
|
-
const maxage =
|
|
97
|
-
const refreshAge =
|
|
98
|
-
const garbageCollectAge =
|
|
99
|
-
const globalState =
|
|
95
|
+
const maxage = options.maxage ?? DEFAULT_MAXAGE;
|
|
96
|
+
const refreshAge = options.refreshAge ?? maxage;
|
|
97
|
+
const garbageCollectAge = options.garbageCollectAge ?? maxage;
|
|
98
|
+
const globalState = useGlobalStateObject();
|
|
100
99
|
|
|
101
100
|
// Server-side logic.
|
|
102
101
|
if (globalState.ssrContext) {
|
|
@@ -118,67 +117,59 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
118
117
|
}
|
|
119
118
|
}
|
|
120
119
|
}
|
|
120
|
+
}
|
|
121
|
+
const {
|
|
122
|
+
disabled
|
|
123
|
+
} = options;
|
|
121
124
|
|
|
122
|
-
|
|
123
|
-
} else {
|
|
124
|
-
const {
|
|
125
|
-
disabled
|
|
126
|
-
} = options;
|
|
127
|
-
|
|
128
|
-
// Reference-counting & garbage collection.
|
|
129
|
-
|
|
130
|
-
const idsHash = hash(ids);
|
|
125
|
+
// Reference-counting & garbage collection.
|
|
131
126
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
}
|
|
127
|
+
const idsString = JSON.stringify(ids);
|
|
128
|
+
useEffect(() => {
|
|
129
|
+
const localIds = JSON.parse(idsString);
|
|
130
|
+
if (!disabled) gcOnWithhold(localIds, path, globalState);
|
|
131
|
+
return () => {
|
|
132
|
+
if (!disabled) {
|
|
133
|
+
gcOnRelease(localIds, path, globalState, garbageCollectAge);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
140
136
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
}, [disabled, garbageCollectAge, globalState, idsHash, path]);
|
|
137
|
+
// `ids` are represented in the dependencies array by `idsHash` value,
|
|
138
|
+
// as useEffect() hook requires a constant size of dependencies array.
|
|
139
|
+
}, [disabled, garbageCollectAge, globalState, idsString, path]);
|
|
145
140
|
|
|
146
|
-
|
|
147
|
-
|
|
141
|
+
// NOTE: a bunch of Rules of Hooks ignored belows because in our very
|
|
142
|
+
// special case the otherwise wrong behavior is actually what we need.
|
|
148
143
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
data: (_state2$data = state2 === null || state2 === void 0 ? void 0 : state2.data) !== null && _state2$data !== void 0 ? _state2$data : null,
|
|
171
|
-
timestamp: (_state2$timestamp2 = state2 === null || state2 === void 0 ? void 0 : state2.timestamp) !== null && _state2$timestamp2 !== void 0 ? _state2$timestamp2 : 0
|
|
172
|
-
});
|
|
173
|
-
}
|
|
144
|
+
// Data loading and refreshing.
|
|
145
|
+
useEffect(() => {
|
|
146
|
+
if (!disabled) {
|
|
147
|
+
void (async () => {
|
|
148
|
+
for (const id_0 of ids) {
|
|
149
|
+
const itemPath_0 = path ? `${path}.${id_0}` : `${id_0}`;
|
|
150
|
+
const state2 = globalState.get(itemPath_0);
|
|
151
|
+
const {
|
|
152
|
+
deps
|
|
153
|
+
} = options;
|
|
154
|
+
if (deps && globalState.hasChangedDependencies(itemPath_0, deps) || refreshAge < Date.now() - (state2?.timestamp ?? 0) && (!state2?.operationId || state2.operationId.startsWith('S'))) {
|
|
155
|
+
if (!deps) globalState.dropDependencies(itemPath_0);
|
|
156
|
+
await loadAsyncData(itemPath_0,
|
|
157
|
+
// TODO: I guess, the loader is not correctly typed here -
|
|
158
|
+
// it can be synchronous, and in that case the following method
|
|
159
|
+
// should be kept synchronous to not alter the sync logic.
|
|
160
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
161
|
+
(old, ...args_0) => loader(id_0, old, ...args_0), globalState, {
|
|
162
|
+
data: state2?.data ?? null,
|
|
163
|
+
timestamp: state2?.timestamp ?? 0
|
|
164
|
+
});
|
|
174
165
|
}
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
166
|
+
}
|
|
167
|
+
})();
|
|
168
|
+
}
|
|
169
|
+
});
|
|
179
170
|
const [localState] = useGlobalState(path, {});
|
|
180
171
|
const ref = useRef(null);
|
|
181
|
-
|
|
172
|
+
ref.current ??= {
|
|
182
173
|
globalState,
|
|
183
174
|
ids,
|
|
184
175
|
loader,
|
|
@@ -196,7 +187,7 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
196
187
|
const reload = async customLoader => {
|
|
197
188
|
const rc = ref.current;
|
|
198
189
|
if (!rc) throw Error('Internal error');
|
|
199
|
-
const localLoader = customLoader
|
|
190
|
+
const localLoader = customLoader ?? rc.loader;
|
|
200
191
|
|
|
201
192
|
// TODO: Revise - not sure all related typing is 100% correct,
|
|
202
193
|
// thus let's keep this runtime assertion.
|
|
@@ -204,17 +195,17 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
204
195
|
if (!localLoader || !rc.globalState || !rc.ids) {
|
|
205
196
|
throw Error('Internal error');
|
|
206
197
|
}
|
|
207
|
-
for (const
|
|
208
|
-
const
|
|
209
|
-
const
|
|
198
|
+
for (const id_1 of rc.ids) {
|
|
199
|
+
const itemPath_1 = rc.path ? `${rc.path}.${id_1}` : `${id_1}`;
|
|
200
|
+
const promiseOrVoid_0 = loadAsyncData(itemPath_1,
|
|
210
201
|
// TODO: Revise! Most probably we don't have fully correct loader
|
|
211
202
|
// typing, as it may return either promise or value, and those two
|
|
212
203
|
// cases call for different runtime behavior, which in turns only
|
|
213
204
|
// happens if the outer function on the next line matches the same
|
|
214
205
|
// async / sync signature.
|
|
215
206
|
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
216
|
-
(oldData, meta) => localLoader(
|
|
217
|
-
if (
|
|
207
|
+
(oldData, meta) => localLoader(id_1, oldData, meta), rc.globalState);
|
|
208
|
+
if (promiseOrVoid_0 instanceof Promise) await promiseOrVoid_0;
|
|
218
209
|
}
|
|
219
210
|
};
|
|
220
211
|
|
|
@@ -224,14 +215,14 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
224
215
|
// happens if the outer function on the next line matches the same
|
|
225
216
|
// async / sync signature.
|
|
226
217
|
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
227
|
-
const reloadSingle =
|
|
218
|
+
const reloadSingle = customLoader_0 => reload(
|
|
228
219
|
// TODO: Revise! Most probably we don't have fully correct loader
|
|
229
220
|
// typing, as it may return either promise or value, and those two
|
|
230
221
|
// cases call for different runtime behavior, which in turns only
|
|
231
222
|
// happens if the outer function on the next line matches the same
|
|
232
223
|
// async / sync signature.
|
|
233
224
|
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
234
|
-
|
|
225
|
+
customLoader_0 && ((id_2, ...args_1) => customLoader_0(...args_1)));
|
|
235
226
|
const setSingle = data => {
|
|
236
227
|
void reload(() => data);
|
|
237
228
|
};
|
|
@@ -241,14 +232,29 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
241
232
|
setSingle
|
|
242
233
|
};
|
|
243
234
|
});
|
|
235
|
+
const [stale, setStale] = useState({});
|
|
236
|
+
|
|
237
|
+
// TODO: Merge into the data-reloading effect above?
|
|
238
|
+
useEffect(() => {
|
|
239
|
+
const now = Date.now();
|
|
240
|
+
const nowStale = {};
|
|
241
|
+
for (const [key, e] of Object.entries(localState)) {
|
|
242
|
+
nowStale[key] = maxage < now - e.timestamp;
|
|
243
|
+
}
|
|
244
|
+
const id_3 = areEqual(stale, nowStale) ? null : requestAnimationFrame(() => {
|
|
245
|
+
setStale(nowStale);
|
|
246
|
+
});
|
|
247
|
+
return () => {
|
|
248
|
+
if (id_3 !== null) cancelAnimationFrame(id_3);
|
|
249
|
+
};
|
|
250
|
+
});
|
|
244
251
|
if (!Array.isArray(idOrIds)) {
|
|
245
|
-
var _e$timestamp, _e$data;
|
|
246
252
|
// TODO: Revise related typings!
|
|
247
|
-
const
|
|
248
|
-
const timestamp =
|
|
253
|
+
const e_0 = localState[idOrIds];
|
|
254
|
+
const timestamp = e_0?.timestamp ?? 0;
|
|
249
255
|
return {
|
|
250
|
-
data:
|
|
251
|
-
loading: !!
|
|
256
|
+
data: stale[idOrIds] ? null : e_0?.data ?? null,
|
|
257
|
+
loading: !!e_0?.operationId,
|
|
252
258
|
reload: stable.reloadSingle,
|
|
253
259
|
set: stable.setSingle,
|
|
254
260
|
timestamp
|
|
@@ -260,19 +266,18 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
260
266
|
reload: stable.reload,
|
|
261
267
|
timestamp: Number.MAX_VALUE
|
|
262
268
|
};
|
|
263
|
-
for (const
|
|
264
|
-
var _e$timestamp2, _e$data2;
|
|
269
|
+
for (const id_4 of ids) {
|
|
265
270
|
// TODO: Revise related typing. Should `localState` have a more specific type?
|
|
266
|
-
const
|
|
267
|
-
const loading = !!
|
|
268
|
-
const
|
|
269
|
-
res.items[
|
|
270
|
-
data:
|
|
271
|
+
const e_1 = localState[id_4];
|
|
272
|
+
const loading = !!e_1?.operationId;
|
|
273
|
+
const timestamp_0 = e_1?.timestamp ?? 0;
|
|
274
|
+
res.items[id_4] = {
|
|
275
|
+
data: stale[id_4] ? null : e_1?.data ?? null,
|
|
271
276
|
loading,
|
|
272
|
-
timestamp
|
|
277
|
+
timestamp: timestamp_0
|
|
273
278
|
};
|
|
274
|
-
res.loading
|
|
275
|
-
if (res.timestamp >
|
|
279
|
+
res.loading ||= loading;
|
|
280
|
+
if (res.timestamp > timestamp_0) res.timestamp = timestamp_0;
|
|
276
281
|
}
|
|
277
282
|
return res;
|
|
278
283
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAsyncCollection.js","names":["id","itemPath","args","promiseOrVoid","customLoader","e","timestamp"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n DEFAULT_MAXAGE,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n loadAsyncData,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n areEqual,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Partial<Record<IdT, AsyncDataEnvelopeT<DataT>>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (id: IdT, oldData: DataT | null, meta: {\n abortSignal: AbortSignal;\n oldDataTimestamp: number;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void> | 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: Record<IdT, CollectionItemT<DataT>>;\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype CurrentT<DataT, IdT extends number | string> = {\n globalState: GlobalState<unknown>;\n ids: IdT[];\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n path: null | string | undefined;\n};\n\ntype StableT<DataT, IdT extends number | string> = {\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n setSingle: (data: DataT | null) => void;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (const id of ids) {\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (const id of ids) {\n res.add(id.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (const [id, envelope] of entries) {\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n // Removes ID duplicates.\n const res = Array.from(new Set(idOrIds));\n\n // Ensures stable ID order.\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n\n return res;\n }\n return [idOrIds];\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}`> = 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}`> = 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\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT>;\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.\n// eslint-disable-next-line complexity\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): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = useGlobalStateObject();\n\n // Server-side logic.\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR) {\n const operationId: OperationIdT = `S${globalThis.crypto.randomUUID()}`;\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n {\n initialValue: newAsyncDataEnvelope<DataT>(),\n },\n );\n if (!state.timestamp && !state.operationId) {\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n itemPath,\n (...args):\n DataT | Promise<DataT | null> | null => loader(id, ...args),\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n operationId,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n }\n }\n\n const { disabled } = options;\n\n // Reference-counting & garbage collection.\n\n const idsString = JSON.stringify(ids);\n\n useEffect(() => {\n const localIds = JSON.parse(idsString) as IdT[];\n\n if (!disabled) gcOnWithhold(localIds, path, globalState);\n return () => {\n if (!disabled) {\n gcOnRelease(localIds, path, globalState, garbageCollectAge);\n }\n };\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n }, [\n disabled,\n garbageCollectAge,\n globalState,\n idsString,\n path,\n ]);\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 useEffect(() => {\n if (!disabled) {\n void (async () => {\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n await loadAsyncData<ForceT, DataT>(\n itemPath,\n // TODO: I guess, the loader is not correctly typed here -\n // it can be synchronous, and in that case the following method\n // should be kept synchronous to not alter the sync logic.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (old, ...args) => loader(id, old, ...args),\n globalState,\n {\n data: state2?.data ?? null,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n }\n });\n\n const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\n\n const ref = useRef<CurrentT<DataT, IdT>>(null);\n\n ref.current ??= {\n globalState,\n ids,\n loader,\n path,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n ids,\n loader,\n path,\n };\n }, [globalState, ids, loader, path]);\n\n const [stable] = useState<StableT<DataT, IdT>>(() => {\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const localLoader = customLoader ?? rc.loader;\n\n // TODO: Revise - not sure all related typing is 100% correct,\n // thus let's keep this runtime assertion.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!localLoader || !rc.globalState || !rc.ids) {\n throw Error('Internal error');\n }\n\n for (const id of rc.ids) {\n const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;\n\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n itemPath,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n rc.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const reloadSingle: AsyncDataReloaderT<DataT> = (customLoader) => reload(\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n\n const setSingle = (data: DataT | null) => {\n void reload(() => data);\n };\n\n return { reload, reloadSingle, setSingle };\n });\n\n const [stale, setStale] = useState({} as Record<IdT, boolean>);\n\n // TODO: Merge into the data-reloading effect above?\n useEffect(() => {\n const now = Date.now();\n const nowStale = {} as Record<IdT, boolean>;\n for (const [key, e] of Object.entries(localState)) {\n nowStale[key as IdT] = maxage < now - e.timestamp;\n }\n\n const id = areEqual(stale, nowStale) ? null : requestAnimationFrame(() => {\n setStale(nowStale);\n });\n\n return () => {\n if (id !== null) cancelAnimationFrame(id);\n };\n });\n\n if (!Array.isArray(idOrIds)) {\n // TODO: Revise related typings!\n const e = localState[idOrIds as string];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: stale[idOrIds] ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: stable.reloadSingle,\n set: stable.setSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: stable.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (const id of ids) {\n // TODO: Revise related typing. Should `localState` have a more specific type?\n const e = localState[id as string];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: stale[id] ? 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\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>\n | UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAAS,SAAS,EAAE,MAAM,EAAE,QAAQ,QAAQ,OAAO;AAAC,SAG3C,oBAAoB;AAAA,SAK3B,cAAc,EAKd,aAAa,EACb,oBAAoB;AAAA,OAGf,cAAc;AAAA,SAMnB,QAAQ,EACR,WAAW;AAkDb;AACA;AACA;AACA;AACA;AACA;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MACL,IAAI,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,IAAI,GAAGA,GAAC,EAAE,IAAI,IAAI,IAAI;MAC7C,OAAO,EAAE,CAAC,CAACA,GAAC,EAAE,WAAW;MACzB,MAAM,EAAE,MAAM,CAAC,YAAY;MAC3B,GAAG,EAAE,MAAM,CAAC,SAAS;MACrB;IACF,CAAC;EACH;EAEA,MAAM,GAAuC,GAAG;IAC9C,KAAK,EAAE,CAAC,CAAwC;IAChD,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,MAAM,CAAC,MAAM;IACrB,SAAS,EAAE,MAAM,CAAC;EACpB,CAAC;EAED,KAAK,MAAML,IAAE,IAAI,GAAG,EAAE;IACpB;IACA,MAAMK,GAAC,GAAG,UAAU,CAACL,IAAE,CAAW;IAClC,MAAM,OAAO,GAAG,CAAC,CAACK,GAAC,EAAE,WAAW;IAChC,MAAMC,WAAS,GAAGD,GAAC,EAAE,SAAS,IAAI,CAAC;IAEnC,GAAG,CAAC,KAAK,CAACL,IAAE,CAAC,GAAG;MACd,IAAI,EAAE,KAAK,CAACA,IAAE,CAAC,GAAG,IAAI,GAAGK,GAAC,EAAE,IAAI,IAAI,IAAI;MACxC,OAAO;MACP,SAAS,EAATC;IACF,CAAC;IACD,GAAG,CAAC,OAAO,KAAK,OAAO;IACvB,IAAI,GAAG,CAAC,SAAS,GAAGA,WAAS,EAAE,GAAG,CAAC,SAAS,GAAGA,WAAS;EAC1D;EAEA,OAAO,GAAG;AACZ;AAEA,eAAe,kBAAkB;;AAEjC","ignoreList":[]}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { c as _c } from "react/compiler-runtime";
|
|
1
2
|
/**
|
|
2
3
|
* Loads and uses async data into the GlobalState path.
|
|
3
4
|
*/
|
|
4
5
|
|
|
5
|
-
import { useEffect, useRef } from 'react';
|
|
6
|
+
import { useEffect, useRef, useState } from 'react';
|
|
6
7
|
import { MIN_MS } from '@dr.pogodin/js-utils';
|
|
7
|
-
import {
|
|
8
|
+
import { useGlobalStateObject } from "./GlobalStateProvider.js";
|
|
8
9
|
import useGlobalState from "./useGlobalState.js";
|
|
9
10
|
import { cloneDeepForLog, isDebugMode } from "./utils.js";
|
|
10
11
|
export const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
|
|
@@ -35,8 +36,8 @@ export function newAsyncDataEnvelope(initialData = null, {
|
|
|
35
36
|
function setState(data, path, gs, prevState = gs.get(path)) {
|
|
36
37
|
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
37
38
|
/* eslint-disable no-console */
|
|
38
|
-
console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path
|
|
39
|
-
console.log('Data:', cloneDeepForLog(data, path
|
|
39
|
+
console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path ?? ''}"`);
|
|
40
|
+
console.log('Data:', cloneDeepForLog(data, path ?? ''));
|
|
40
41
|
/* eslint-enable no-console */
|
|
41
42
|
}
|
|
42
43
|
gs.set(path, {
|
|
@@ -61,7 +62,7 @@ function finalizeLoad(data, path, gs, operationId) {
|
|
|
61
62
|
// set up, thus it should be cleaned out here.
|
|
62
63
|
gs.asyncDataLoadDone(operationId, false);
|
|
63
64
|
const state = gs.get(path);
|
|
64
|
-
if (operationId ===
|
|
65
|
+
if (operationId === state?.operationId) setState(data, path, gs, state);
|
|
65
66
|
}
|
|
66
67
|
/**
|
|
67
68
|
* Executes the data loading operation.
|
|
@@ -85,7 +86,7 @@ export function loadAsyncData(path, loader, globalState, old,
|
|
|
85
86
|
operationId = `C${globalThis.crypto.randomUUID()}`) {
|
|
86
87
|
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
87
88
|
/* eslint-disable no-console */
|
|
88
|
-
console.log(`ReactGlobalState: async data (re-)loading. Path: "${path
|
|
89
|
+
console.log(`ReactGlobalState: async data (re-)loading. Path: "${path ?? ''}"`);
|
|
89
90
|
/* eslint-enable no-console */
|
|
90
91
|
}
|
|
91
92
|
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
@@ -133,33 +134,72 @@ operationId = `C${globalThis.crypto.randomUUID()}`) {
|
|
|
133
134
|
// TODO: Perhaps split the heap management to a dedicated hook,
|
|
134
135
|
// as it is done inside useAsyncCollection().
|
|
135
136
|
|
|
136
|
-
function useAsyncData(path, loader,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
137
|
+
function useAsyncData(path, loader, t0) {
|
|
138
|
+
const $ = _c(38);
|
|
139
|
+
let t1;
|
|
140
|
+
if ($[0] !== t0) {
|
|
141
|
+
t1 = t0 === undefined ? {} : t0;
|
|
142
|
+
$[0] = t0;
|
|
143
|
+
$[1] = t1;
|
|
144
|
+
} else {
|
|
145
|
+
t1 = $[1];
|
|
146
|
+
}
|
|
147
|
+
const options = t1;
|
|
148
|
+
const maxage = options.maxage ?? DEFAULT_MAXAGE;
|
|
149
|
+
const refreshAge = options.refreshAge ?? maxage;
|
|
150
|
+
const garbageCollectAge = options.garbageCollectAge ?? maxage;
|
|
151
|
+
const globalState = useGlobalStateObject();
|
|
145
152
|
const state = globalState.get(path, {
|
|
146
153
|
initialValue: newAsyncDataEnvelope()
|
|
147
154
|
});
|
|
155
|
+
let t2;
|
|
156
|
+
if ($[2] !== globalState || $[3] !== loader || $[4] !== path) {
|
|
157
|
+
t2 = {
|
|
158
|
+
globalState,
|
|
159
|
+
loader,
|
|
160
|
+
path
|
|
161
|
+
};
|
|
162
|
+
$[2] = globalState;
|
|
163
|
+
$[3] = loader;
|
|
164
|
+
$[4] = path;
|
|
165
|
+
$[5] = t2;
|
|
166
|
+
} else {
|
|
167
|
+
t2 = $[5];
|
|
168
|
+
}
|
|
148
169
|
const {
|
|
149
170
|
current: heap
|
|
150
|
-
} = useRef(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
171
|
+
} = useRef(t2);
|
|
172
|
+
let t3;
|
|
173
|
+
if ($[6] !== globalState || $[7] !== loader || $[8] !== path) {
|
|
174
|
+
t3 = () => {
|
|
175
|
+
heap.globalState = globalState;
|
|
176
|
+
heap.path = path;
|
|
177
|
+
heap.loader = loader;
|
|
178
|
+
};
|
|
179
|
+
$[6] = globalState;
|
|
180
|
+
$[7] = loader;
|
|
181
|
+
$[8] = path;
|
|
182
|
+
$[9] = t3;
|
|
183
|
+
} else {
|
|
184
|
+
t3 = $[9];
|
|
185
|
+
}
|
|
186
|
+
useEffect(t3);
|
|
187
|
+
let t4;
|
|
188
|
+
if ($[10] === Symbol.for("react.memo_cache_sentinel")) {
|
|
189
|
+
t4 = () => ({
|
|
190
|
+
reload: customLoader => {
|
|
191
|
+
const localLoader = customLoader ?? heap.loader;
|
|
192
|
+
return loadAsyncData(heap.path, localLoader, heap.globalState);
|
|
193
|
+
},
|
|
194
|
+
set: data => {
|
|
195
|
+
setState(data, heap.path, heap.globalState);
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
$[10] = t4;
|
|
199
|
+
} else {
|
|
200
|
+
t4 = $[10];
|
|
201
|
+
}
|
|
202
|
+
const [stable] = useState(t4);
|
|
163
203
|
if (globalState.ssrContext) {
|
|
164
204
|
if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
|
|
165
205
|
const promiseOrVoid = loadAsyncData(path, loader, globalState, {
|
|
@@ -170,23 +210,15 @@ function useAsyncData(path, loader, options = {}) {
|
|
|
170
210
|
globalState.ssrContext.pending.push(promiseOrVoid);
|
|
171
211
|
}
|
|
172
212
|
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
// but as the condition is actually server-side or client-side environment,
|
|
183
|
-
// it is effectively non-conditional at the runtime.
|
|
184
|
-
//
|
|
185
|
-
// TODO: Though, maybe there is a way to refactor it into a cleaner code.
|
|
186
|
-
// The same applies to other useEffect() hooks below.
|
|
187
|
-
useEffect(() => {
|
|
188
|
-
// eslint-disable-line react-hooks/rules-of-hooks
|
|
189
|
-
const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
|
|
213
|
+
}
|
|
214
|
+
const {
|
|
215
|
+
disabled
|
|
216
|
+
} = options;
|
|
217
|
+
let t5;
|
|
218
|
+
let t6;
|
|
219
|
+
if ($[11] !== disabled || $[12] !== garbageCollectAge || $[13] !== globalState || $[14] !== path) {
|
|
220
|
+
t5 = () => {
|
|
221
|
+
const numRefsPath = path ? `${path}.numRefs` : "numRefs";
|
|
190
222
|
if (!disabled) {
|
|
191
223
|
const numRefs = globalState.get(numRefsPath);
|
|
192
224
|
globalState.set(numRefsPath, numRefs + 1);
|
|
@@ -195,12 +227,10 @@ function useAsyncData(path, loader, options = {}) {
|
|
|
195
227
|
if (!disabled) {
|
|
196
228
|
const state2 = globalState.get(path);
|
|
197
229
|
if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
|
|
198
|
-
if (process.env.NODE_ENV !==
|
|
199
|
-
|
|
200
|
-
console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path !== null && path !== void 0 ? path : ''}`);
|
|
201
|
-
/* eslint-enable no-console */
|
|
230
|
+
if (process.env.NODE_ENV !== "production" && isDebugMode()) {
|
|
231
|
+
console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path ?? ""}`);
|
|
202
232
|
}
|
|
203
|
-
globalState.dropDependencies(path
|
|
233
|
+
globalState.dropDependencies(path ?? "");
|
|
204
234
|
globalState.set(path, {
|
|
205
235
|
...state2,
|
|
206
236
|
data: null,
|
|
@@ -212,43 +242,109 @@ function useAsyncData(path, loader, options = {}) {
|
|
|
212
242
|
}
|
|
213
243
|
}
|
|
214
244
|
};
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
245
|
+
};
|
|
246
|
+
t6 = [disabled, garbageCollectAge, globalState, path];
|
|
247
|
+
$[11] = disabled;
|
|
248
|
+
$[12] = garbageCollectAge;
|
|
249
|
+
$[13] = globalState;
|
|
250
|
+
$[14] = path;
|
|
251
|
+
$[15] = t5;
|
|
252
|
+
$[16] = t6;
|
|
253
|
+
} else {
|
|
254
|
+
t5 = $[15];
|
|
255
|
+
t6 = $[16];
|
|
256
|
+
}
|
|
257
|
+
useEffect(t5, t6);
|
|
258
|
+
let t7;
|
|
259
|
+
if ($[17] !== disabled || $[18] !== globalState || $[19] !== loader || $[20] !== options || $[21] !== path || $[22] !== refreshAge) {
|
|
260
|
+
t7 = () => {
|
|
223
261
|
if (!disabled) {
|
|
224
|
-
const
|
|
262
|
+
const state2_0 = globalState.get(path);
|
|
225
263
|
const {
|
|
226
264
|
deps
|
|
227
265
|
} = options;
|
|
228
|
-
if (
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
if (!deps) globalState.dropDependencies(path !== null && path !== void 0 ? path : '');
|
|
236
|
-
void loadAsyncData(path, loader, globalState, {
|
|
237
|
-
data: state2.data,
|
|
238
|
-
timestamp: state2.timestamp
|
|
266
|
+
if (deps && globalState.hasChangedDependencies(path ?? "", deps) || refreshAge < Date.now() - state2_0.timestamp && (!state2_0.operationId || state2_0.operationId.startsWith("S"))) {
|
|
267
|
+
if (!deps) {
|
|
268
|
+
globalState.dropDependencies(path ?? "");
|
|
269
|
+
}
|
|
270
|
+
loadAsyncData(path, loader, globalState, {
|
|
271
|
+
data: state2_0.data,
|
|
272
|
+
timestamp: state2_0.timestamp
|
|
239
273
|
});
|
|
240
274
|
}
|
|
241
275
|
}
|
|
242
|
-
}
|
|
276
|
+
};
|
|
277
|
+
$[17] = disabled;
|
|
278
|
+
$[18] = globalState;
|
|
279
|
+
$[19] = loader;
|
|
280
|
+
$[20] = options;
|
|
281
|
+
$[21] = path;
|
|
282
|
+
$[22] = refreshAge;
|
|
283
|
+
$[23] = t7;
|
|
284
|
+
} else {
|
|
285
|
+
t7 = $[23];
|
|
243
286
|
}
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
287
|
+
useEffect(t7);
|
|
288
|
+
let t8;
|
|
289
|
+
if ($[24] === Symbol.for("react.memo_cache_sentinel")) {
|
|
290
|
+
t8 = newAsyncDataEnvelope();
|
|
291
|
+
$[24] = t8;
|
|
292
|
+
} else {
|
|
293
|
+
t8 = $[24];
|
|
294
|
+
}
|
|
295
|
+
const [localState] = useGlobalState(path, t8);
|
|
296
|
+
let t9;
|
|
297
|
+
if ($[25] !== localState.timestamp || $[26] !== maxage) {
|
|
298
|
+
t9 = () => maxage < Date.now() - localState.timestamp;
|
|
299
|
+
$[25] = localState.timestamp;
|
|
300
|
+
$[26] = maxage;
|
|
301
|
+
$[27] = t9;
|
|
302
|
+
} else {
|
|
303
|
+
t9 = $[27];
|
|
304
|
+
}
|
|
305
|
+
const [stale, setStale] = useState(t9);
|
|
306
|
+
let t10;
|
|
307
|
+
if ($[28] !== localState.timestamp || $[29] !== maxage || $[30] !== stale) {
|
|
308
|
+
t10 = () => {
|
|
309
|
+
const nowStale = maxage < Date.now() - localState.timestamp;
|
|
310
|
+
const id = stale === nowStale ? null : requestAnimationFrame(() => {
|
|
311
|
+
setStale(nowStale);
|
|
312
|
+
});
|
|
313
|
+
return () => {
|
|
314
|
+
if (id !== null) {
|
|
315
|
+
cancelAnimationFrame(id);
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
};
|
|
319
|
+
$[28] = localState.timestamp;
|
|
320
|
+
$[29] = maxage;
|
|
321
|
+
$[30] = stale;
|
|
322
|
+
$[31] = t10;
|
|
323
|
+
} else {
|
|
324
|
+
t10 = $[31];
|
|
325
|
+
}
|
|
326
|
+
useEffect(t10);
|
|
327
|
+
const t11 = stale ? null : localState.data;
|
|
328
|
+
const t12 = !!localState.operationId;
|
|
329
|
+
let t13;
|
|
330
|
+
if ($[32] !== localState.timestamp || $[33] !== stable.reload || $[34] !== stable.set || $[35] !== t11 || $[36] !== t12) {
|
|
331
|
+
t13 = {
|
|
332
|
+
data: t11,
|
|
333
|
+
loading: t12,
|
|
334
|
+
reload: stable.reload,
|
|
335
|
+
set: stable.set,
|
|
336
|
+
timestamp: localState.timestamp
|
|
337
|
+
};
|
|
338
|
+
$[32] = localState.timestamp;
|
|
339
|
+
$[33] = stable.reload;
|
|
340
|
+
$[34] = stable.set;
|
|
341
|
+
$[35] = t11;
|
|
342
|
+
$[36] = t12;
|
|
343
|
+
$[37] = t13;
|
|
344
|
+
} else {
|
|
345
|
+
t13 = $[37];
|
|
346
|
+
}
|
|
347
|
+
return t13;
|
|
252
348
|
}
|
|
253
349
|
export { useAsyncData };
|
|
254
350
|
|