@choksheak/react-utils 0.4.4 → 0.4.5
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/NoSSR.cjs +30 -7
- package/NoSSR.min.cjs +1 -1
- package/NoSSR.min.cjs.map +1 -1
- package/NoSSR.min.mjs +1 -1
- package/NoSSR.min.mjs.map +1 -1
- package/NoSSR.mjs +0 -2
- package/index.cjs +979 -43
- package/index.d.cts +1 -1
- package/index.d.ts +1 -1
- package/index.min.cjs +1 -1
- package/index.min.cjs.map +1 -1
- package/index.min.mjs +1 -1
- package/index.min.mjs.map +1 -1
- package/index.mjs +916 -25
- package/package.json +1 -41
- package/sharedQuery.cjs +938 -10
- package/sharedQuery.d.cts +21 -20
- package/sharedQuery.d.ts +21 -20
- package/sharedQuery.min.cjs +1 -1
- package/sharedQuery.min.cjs.map +1 -1
- package/sharedQuery.min.mjs +1 -1
- package/sharedQuery.min.mjs.map +1 -1
- package/sharedQuery.mjs +906 -10
- package/sharedState.cjs +326 -15
- package/sharedState.min.cjs +1 -1
- package/sharedState.min.cjs.map +1 -1
- package/sharedState.min.mjs +1 -1
- package/sharedState.min.mjs.map +1 -1
- package/sharedState.mjs +291 -10
- package/storage.cjs +129 -10
- package/storage.min.cjs +1 -1
- package/storage.min.cjs.map +1 -1
- package/storage.min.mjs +1 -1
- package/storage.min.mjs.map +1 -1
- package/storage.mjs +98 -6
- package/stringify.cjs +57 -6
- package/stringify.min.cjs +1 -1
- package/stringify.min.cjs.map +1 -1
- package/stringify.min.mjs +1 -1
- package/stringify.min.mjs.map +1 -1
- package/stringify.mjs +30 -4
- package/useDeepMemo.cjs +40 -6
- package/useDeepMemo.min.cjs +1 -1
- package/useDeepMemo.min.cjs.map +1 -1
- package/useDeepMemo.min.mjs +1 -1
- package/useDeepMemo.min.mjs.map +1 -1
- package/useDeepMemo.mjs +13 -4
- package/chunk-4235I4VO.mjs +0 -34
- package/chunk-433OAJVP.min.cjs +0 -2
- package/chunk-433OAJVP.min.cjs.map +0 -1
- package/chunk-4J7TN5JN.mjs +0 -17
- package/chunk-5PDGU37E.cjs +0 -104
- package/chunk-7D2YNZO3.cjs +0 -577
- package/chunk-BQIRLDQC.min.mjs +0 -2
- package/chunk-BQIRLDQC.min.mjs.map +0 -1
- package/chunk-CYTO5EZE.cjs +0 -34
- package/chunk-FXCYHS3L.mjs +0 -577
- package/chunk-HRE7YPUJ.min.mjs +0 -2
- package/chunk-HRE7YPUJ.min.mjs.map +0 -1
- package/chunk-IS3BZTWE.cjs +0 -35
- package/chunk-JOHZV3FD.min.cjs +0 -2
- package/chunk-JOHZV3FD.min.cjs.map +0 -1
- package/chunk-KGN4HQPP.min.cjs +0 -2
- package/chunk-KGN4HQPP.min.cjs.map +0 -1
- package/chunk-NGGNAAHA.cjs +0 -203
- package/chunk-NL4FU2MJ.min.mjs +0 -2
- package/chunk-NL4FU2MJ.min.mjs.map +0 -1
- package/chunk-PHLY3LR4.mjs +0 -104
- package/chunk-R7POPVJR.mjs +0 -35
- package/chunk-RP2TWHFU.min.cjs +0 -2
- package/chunk-RP2TWHFU.min.cjs.map +0 -1
- package/chunk-TI3FMEYP.min.mjs +0 -2
- package/chunk-TI3FMEYP.min.mjs.map +0 -1
- package/chunk-UFJQLQFI.min.cjs +0 -2
- package/chunk-UFJQLQFI.min.cjs.map +0 -1
- package/chunk-VHMO75EY.min.mjs +0 -2
- package/chunk-VHMO75EY.min.mjs.map +0 -1
- package/chunk-WXLUEDBO.cjs +0 -17
- package/chunk-XRHQCN2J.min.mjs +0 -2
- package/chunk-XRHQCN2J.min.mjs.map +0 -1
- package/chunk-YHU4KW2D.mjs +0 -203
- package/chunk-ZCDXPV3A.min.cjs +0 -2
- package/chunk-ZCDXPV3A.min.cjs.map +0 -1
- package/dist-O6NNX4Y3.min.mjs +0 -2
- package/dist-O6NNX4Y3.min.mjs.map +0 -1
- package/dist-SEGTJ72R.min.cjs +0 -2
- package/dist-SEGTJ72R.min.cjs.map +0 -1
- package/dist-UKP7SPWZ.cjs +0 -545
- package/dist-YXYQDOH5.mjs +0 -545
- package/magic-string.es-5QZEPJXJ.min.mjs +0 -14
- package/magic-string.es-5QZEPJXJ.min.mjs.map +0 -1
- package/magic-string.es-EREYSDLL.mjs +0 -1308
- package/magic-string.es-FXUUD55Y.min.cjs +0 -14
- package/magic-string.es-FXUUD55Y.min.cjs.map +0 -1
- package/magic-string.es-HC5PDAU3.cjs +0 -1308
package/index.mjs
CHANGED
|
@@ -1,29 +1,920 @@
|
|
|
1
|
+
// src/sharedQuery.ts
|
|
2
|
+
import { http, retries } from "@choksheak/ts-utils/http";
|
|
3
|
+
import { nonNil } from "@choksheak/ts-utils/nonNil";
|
|
4
|
+
import getByteSize from "object-sizeof";
|
|
1
5
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
import {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
6
|
+
useCallback,
|
|
7
|
+
useEffect,
|
|
8
|
+
useMemo as useMemo2,
|
|
9
|
+
useRef,
|
|
10
|
+
useState as useState2
|
|
11
|
+
} from "react";
|
|
12
|
+
import XXH from "xxhashjs";
|
|
13
|
+
|
|
14
|
+
// src/sharedState.ts
|
|
15
|
+
import { MS_PER_DAY } from "@choksheak/ts-utils/timeConstants";
|
|
16
|
+
import { useSyncExternalStore } from "react";
|
|
17
|
+
|
|
18
|
+
// src/storage.ts
|
|
19
|
+
import { kvStore } from "@choksheak/ts-utils/kvStore";
|
|
20
|
+
import { createLocalStore } from "@choksheak/ts-utils/localStore";
|
|
21
|
+
var IS_NOT_BROWSER = typeof window === "undefined";
|
|
22
|
+
function getStorageAdapter(options, defaultStoreExpiryMs) {
|
|
23
|
+
const { store } = options ?? {};
|
|
24
|
+
if (!store) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
|
|
28
|
+
const expiryMs = store.expiryMs || defaultStoreExpiryMs;
|
|
29
|
+
const config = { ...store, expiryMs };
|
|
30
|
+
switch (store.persistTo) {
|
|
31
|
+
case "localStorage":
|
|
32
|
+
return localStoreAdapter(config);
|
|
33
|
+
case "indexedDb":
|
|
34
|
+
return kvStoreAdapter(config);
|
|
35
|
+
default:
|
|
36
|
+
store.persistTo;
|
|
37
|
+
throw new Error(`Unknown store.adapter ${store.persistTo}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return store;
|
|
41
|
+
}
|
|
42
|
+
function localStoreAdapter({
|
|
43
|
+
key,
|
|
44
|
+
expiryMs,
|
|
45
|
+
isValid
|
|
46
|
+
}) {
|
|
47
|
+
const STORE_NAME = "react-utils";
|
|
48
|
+
const adapter = createLocalStore(STORE_NAME, {
|
|
49
|
+
defaultExpiryMs: expiryMs
|
|
50
|
+
});
|
|
51
|
+
const keyPrefix = key + ":";
|
|
52
|
+
return {
|
|
53
|
+
set: (key2, value) => {
|
|
54
|
+
if (IS_NOT_BROWSER) return;
|
|
55
|
+
adapter.set(keyPrefix + key2, value);
|
|
56
|
+
},
|
|
57
|
+
get: (key2) => {
|
|
58
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
59
|
+
const fullKey = keyPrefix + key2;
|
|
60
|
+
const value = adapter.get(fullKey);
|
|
61
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
62
|
+
console.warn(
|
|
63
|
+
`localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`
|
|
64
|
+
);
|
|
65
|
+
adapter.delete(fullKey);
|
|
66
|
+
return void 0;
|
|
67
|
+
}
|
|
68
|
+
return value;
|
|
69
|
+
},
|
|
70
|
+
delete: (key2) => {
|
|
71
|
+
if (IS_NOT_BROWSER) return;
|
|
72
|
+
adapter.delete(keyPrefix + key2);
|
|
73
|
+
},
|
|
74
|
+
/** Note that this will clear all keys in all shared states. */
|
|
75
|
+
clear: () => {
|
|
76
|
+
if (IS_NOT_BROWSER) return;
|
|
77
|
+
adapter.clear();
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function kvStoreAdapter({
|
|
82
|
+
key,
|
|
83
|
+
expiryMs,
|
|
84
|
+
isValid
|
|
85
|
+
}) {
|
|
86
|
+
const keyPrefix = key + ":";
|
|
87
|
+
return {
|
|
88
|
+
set: async (key2, value) => {
|
|
89
|
+
if (IS_NOT_BROWSER) return;
|
|
90
|
+
await kvStore.set(keyPrefix + key2, value, expiryMs);
|
|
91
|
+
},
|
|
92
|
+
get: async (key2) => {
|
|
93
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
94
|
+
const fullKey = keyPrefix + key2;
|
|
95
|
+
const value = await kvStore.get(fullKey);
|
|
96
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
97
|
+
console.warn(
|
|
98
|
+
`indexedDb adapter: Auto-discard invalid value for ${key2}:`,
|
|
99
|
+
value
|
|
100
|
+
);
|
|
101
|
+
await kvStore.delete(fullKey);
|
|
102
|
+
return void 0;
|
|
103
|
+
}
|
|
104
|
+
return value;
|
|
105
|
+
},
|
|
106
|
+
delete: async (key2) => {
|
|
107
|
+
if (IS_NOT_BROWSER) return;
|
|
108
|
+
await kvStore.delete(keyPrefix + key2);
|
|
109
|
+
},
|
|
110
|
+
clear: async () => {
|
|
111
|
+
if (IS_NOT_BROWSER) return;
|
|
112
|
+
await kvStore.clear();
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// src/sharedState.ts
|
|
118
|
+
var SharedStateConfig = {
|
|
119
|
+
/**
|
|
120
|
+
* Default duration for storage expiration in milliseconds. Initial value
|
|
121
|
+
* is 30 days, but can be changed to anything.
|
|
122
|
+
*/
|
|
123
|
+
storeExpiryMs: 30 * MS_PER_DAY,
|
|
124
|
+
/**
|
|
125
|
+
* True to load from storage only on mount, false (default) to load in
|
|
126
|
+
* the top level scope when the shared state is defined.
|
|
127
|
+
*/
|
|
128
|
+
lazyLoad: false
|
|
129
|
+
};
|
|
130
|
+
function configureSharedState(config) {
|
|
131
|
+
Object.assign(SharedStateConfig, config);
|
|
132
|
+
}
|
|
133
|
+
function createPubSubStore() {
|
|
134
|
+
const dataByKey = /* @__PURE__ */ new Map();
|
|
135
|
+
const subscribersByKey = /* @__PURE__ */ new Map();
|
|
136
|
+
function notify(key, next, prev) {
|
|
137
|
+
const subscribers = subscribersByKey.get(key);
|
|
138
|
+
if (!subscribers) return;
|
|
139
|
+
const copy = Array.from(subscribers.values());
|
|
140
|
+
for (const subscriber of copy) {
|
|
141
|
+
try {
|
|
142
|
+
subscriber(next, prev);
|
|
143
|
+
} catch (e) {
|
|
144
|
+
console.error(`Error invoking subscriber:`, e);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
// This could be undefined if T includes undefined, else it should never
|
|
150
|
+
// return undefined because the user has to always specify the default value.
|
|
151
|
+
get(key) {
|
|
152
|
+
return dataByKey.get(key);
|
|
153
|
+
},
|
|
154
|
+
set(key, value) {
|
|
155
|
+
const prev = dataByKey.get(key);
|
|
156
|
+
if (prev === value) return;
|
|
157
|
+
dataByKey.set(key, value);
|
|
158
|
+
notify(key, value, prev);
|
|
159
|
+
},
|
|
160
|
+
delete(key) {
|
|
161
|
+
dataByKey.delete(key);
|
|
162
|
+
},
|
|
163
|
+
setNoNotify(key, value) {
|
|
164
|
+
dataByKey.set(key, value);
|
|
165
|
+
},
|
|
166
|
+
// Subscribe to changes of a specific key
|
|
167
|
+
subscribe(key, subscriber) {
|
|
168
|
+
let subscribers = subscribersByKey.get(key);
|
|
169
|
+
if (!subscribers) {
|
|
170
|
+
subscribers = /* @__PURE__ */ new Set();
|
|
171
|
+
subscribersByKey.set(key, subscribers);
|
|
172
|
+
}
|
|
173
|
+
subscribers.add(subscriber);
|
|
174
|
+
return () => {
|
|
175
|
+
subscribers.delete(subscriber);
|
|
176
|
+
if (subscribers.size === 0) subscribersByKey.delete(key);
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function getOrCreatePubSubStore() {
|
|
182
|
+
if (typeof window !== "undefined") {
|
|
183
|
+
const t = window.globalThis;
|
|
184
|
+
return t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore());
|
|
185
|
+
}
|
|
186
|
+
return createPubSubStore();
|
|
187
|
+
}
|
|
188
|
+
var pubSubStore = getOrCreatePubSubStore();
|
|
189
|
+
var STORAGE_KEY = "state";
|
|
190
|
+
var stateKey = 0;
|
|
191
|
+
function sharedState(defaultValue, options) {
|
|
192
|
+
let readyResolve = () => {
|
|
193
|
+
};
|
|
194
|
+
const readyPromise = new Promise((resolve) => {
|
|
195
|
+
readyResolve = resolve;
|
|
196
|
+
});
|
|
197
|
+
const resolveReadyPromise = readyResolve;
|
|
198
|
+
const pubSubKey = String(stateKey++);
|
|
199
|
+
const storageAdapter = getStorageAdapter(
|
|
200
|
+
options,
|
|
201
|
+
SharedStateConfig.storeExpiryMs
|
|
202
|
+
);
|
|
203
|
+
pubSubStore.setNoNotify(pubSubKey, defaultValue);
|
|
204
|
+
const lazyLoad = options?.lazyLoad;
|
|
205
|
+
const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
|
|
206
|
+
function completeInit(stored) {
|
|
207
|
+
const value = stored !== void 0 ? stored : defaultValue;
|
|
208
|
+
pubSubStore.set(pubSubKey, value);
|
|
209
|
+
obj.initDone = true;
|
|
210
|
+
resolveReadyPromise();
|
|
211
|
+
}
|
|
212
|
+
const obj = {
|
|
213
|
+
defaultValue,
|
|
214
|
+
/** Allow users to await for the completion of data init. */
|
|
215
|
+
readyPromise,
|
|
216
|
+
lazy,
|
|
217
|
+
initStarted: false,
|
|
218
|
+
initDone: false,
|
|
219
|
+
/** `subscribe` function required by useSyncExternalStore. */
|
|
220
|
+
subscribe(subscriber) {
|
|
221
|
+
return pubSubStore.subscribe(pubSubKey, () => subscriber());
|
|
222
|
+
},
|
|
223
|
+
/** Returns true if there is a backing store. */
|
|
224
|
+
hasStore() {
|
|
225
|
+
return Boolean(storageAdapter);
|
|
226
|
+
},
|
|
227
|
+
/**
|
|
228
|
+
* Set a value directly into the store. Does nothing if there is no
|
|
229
|
+
* backing store.
|
|
230
|
+
*
|
|
231
|
+
* Warning: If you want to set the value properly, you should use
|
|
232
|
+
* `setValue()` instead which also updates the in-memory copy.
|
|
233
|
+
*/
|
|
234
|
+
setInStore(value) {
|
|
235
|
+
return storageAdapter?.set(STORAGE_KEY, value);
|
|
236
|
+
},
|
|
237
|
+
/**
|
|
238
|
+
* Get a value directly from the store. Returns undefined if there is no
|
|
239
|
+
* backing store.
|
|
240
|
+
*/
|
|
241
|
+
getFromStore() {
|
|
242
|
+
return storageAdapter?.get(STORAGE_KEY);
|
|
243
|
+
},
|
|
244
|
+
/**
|
|
245
|
+
* Get the value of the shared state.
|
|
246
|
+
* `getSnapshot` function — must return same ref if value unchanged.
|
|
247
|
+
* Note that this would return the default value if data init from store is
|
|
248
|
+
* not completed yet.
|
|
249
|
+
*/
|
|
250
|
+
getSnapshot() {
|
|
251
|
+
return pubSubStore.get(pubSubKey);
|
|
252
|
+
},
|
|
253
|
+
/** Set the value of the shared state. */
|
|
254
|
+
setValue(next) {
|
|
255
|
+
if (typeof next === "function") {
|
|
256
|
+
const prev = pubSubStore.get(pubSubKey);
|
|
257
|
+
next = next(prev);
|
|
258
|
+
}
|
|
259
|
+
pubSubStore.set(pubSubKey, next);
|
|
260
|
+
void obj.setInStore(next);
|
|
261
|
+
},
|
|
262
|
+
/**
|
|
263
|
+
* Remove the value of the shared state. Actually this just sets the value
|
|
264
|
+
* back to the given default value.
|
|
265
|
+
*/
|
|
266
|
+
delete() {
|
|
267
|
+
pubSubStore.set(pubSubKey, defaultValue);
|
|
268
|
+
return storageAdapter?.set(STORAGE_KEY, defaultValue);
|
|
269
|
+
},
|
|
270
|
+
/** Initial default handling. */
|
|
271
|
+
initDefaultValueOnce() {
|
|
272
|
+
if (obj.initDone || obj.initStarted) return;
|
|
273
|
+
obj.initStarted = true;
|
|
274
|
+
const maybePromise = obj.getFromStore();
|
|
275
|
+
if (maybePromise instanceof Promise) {
|
|
276
|
+
return maybePromise.then(completeInit);
|
|
277
|
+
} else {
|
|
278
|
+
const stored = maybePromise;
|
|
279
|
+
completeInit(stored);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
if (!lazy) {
|
|
284
|
+
obj.initDefaultValueOnce();
|
|
285
|
+
}
|
|
286
|
+
return obj;
|
|
287
|
+
}
|
|
288
|
+
function useSharedState(state) {
|
|
289
|
+
void state.initDefaultValueOnce();
|
|
290
|
+
const value = useSyncExternalStore(
|
|
291
|
+
(onStoreChange) => state.subscribe(onStoreChange),
|
|
292
|
+
() => state.getSnapshot(),
|
|
293
|
+
// getServerSnapshot is needed to prevent SSR dev errors in nextjs.
|
|
294
|
+
() => state.getSnapshot()
|
|
295
|
+
);
|
|
296
|
+
return [value, state.setValue];
|
|
297
|
+
}
|
|
298
|
+
function useSharedStateValue(state) {
|
|
299
|
+
return useSharedState(state)[0];
|
|
300
|
+
}
|
|
301
|
+
function useSharedStateSetter(state) {
|
|
302
|
+
void state.initDefaultValueOnce();
|
|
303
|
+
return state.setValue;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// src/stringify.ts
|
|
307
|
+
function stringifyDeterministicForKeys(params) {
|
|
308
|
+
const cache = /* @__PURE__ */ new Set();
|
|
309
|
+
return JSON.stringify(params, (_, value) => {
|
|
310
|
+
if (typeof value === "function") {
|
|
311
|
+
throw new Error(`Functions should not be passed into query parameters`);
|
|
312
|
+
}
|
|
313
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
314
|
+
return value;
|
|
315
|
+
}
|
|
316
|
+
if (cache.has(value)) {
|
|
317
|
+
return "[Circular]";
|
|
318
|
+
}
|
|
319
|
+
cache.add(value);
|
|
320
|
+
if (value !== params) {
|
|
321
|
+
try {
|
|
322
|
+
JSON.stringify(value);
|
|
323
|
+
} catch {
|
|
324
|
+
return "[Unserializable]";
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return Object.keys(value).sort().reduce(
|
|
328
|
+
(result, key) => {
|
|
329
|
+
result[key] = value[key];
|
|
330
|
+
return result;
|
|
331
|
+
},
|
|
332
|
+
{}
|
|
333
|
+
);
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// src/useDeepMemo.ts
|
|
338
|
+
import { isEqual } from "lodash-es";
|
|
339
|
+
import { useMemo, useState } from "react";
|
|
340
|
+
function useDeepMemo(value) {
|
|
341
|
+
const [state, setState] = useState(value);
|
|
342
|
+
return useMemo(() => {
|
|
343
|
+
if (isEqual(state, value)) {
|
|
344
|
+
return state;
|
|
345
|
+
}
|
|
346
|
+
setState(value);
|
|
347
|
+
return value;
|
|
348
|
+
}, [state, value]);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// src/sharedQuery.ts
|
|
352
|
+
var SharedQueryConfig = {
|
|
353
|
+
/** Refetch on every page load. */
|
|
354
|
+
staleMs: 0,
|
|
355
|
+
/** Keep in cache for a long time. */
|
|
356
|
+
expiryMs: 30 * 864e5,
|
|
357
|
+
/** Always refetch automatically if the data is stale. */
|
|
358
|
+
refetchOnStale: true,
|
|
359
|
+
/** No default persistence configured. */
|
|
360
|
+
persistTo: void 0,
|
|
361
|
+
/** 100 is not too large, but please tweak accordingly. */
|
|
362
|
+
maxSize: 100,
|
|
363
|
+
/** 100kb limit before discarding old records. */
|
|
364
|
+
maxBytes: 1e5,
|
|
365
|
+
/** Default to log to console. */
|
|
366
|
+
log: (...args) => console.log("[sharedQuery]", ...args)
|
|
367
|
+
};
|
|
368
|
+
function configureSharedQuery(config) {
|
|
369
|
+
Object.assign(SharedQueryConfig, config);
|
|
370
|
+
}
|
|
371
|
+
var moduleQueryRegistry = /* @__PURE__ */ new Map();
|
|
372
|
+
function getOrCreateQueryRegistry() {
|
|
373
|
+
if (typeof window !== "undefined") {
|
|
374
|
+
const g = window.globalThis;
|
|
375
|
+
return g.reactUtilsQueryRegistry ??= /* @__PURE__ */ new Map();
|
|
376
|
+
}
|
|
377
|
+
return moduleQueryRegistry;
|
|
378
|
+
}
|
|
379
|
+
function sharedQuery1(options) {
|
|
380
|
+
const registry = getOrCreateQueryRegistry();
|
|
381
|
+
const key = options.queryName || options.url;
|
|
382
|
+
const existing = registry.get(
|
|
383
|
+
options.queryName || options.url
|
|
384
|
+
);
|
|
385
|
+
if (existing) {
|
|
386
|
+
return existing;
|
|
387
|
+
}
|
|
388
|
+
const obj = sharedQuery2(options);
|
|
389
|
+
registry.set(key, obj);
|
|
390
|
+
return obj;
|
|
391
|
+
}
|
|
392
|
+
function sharedQuery2(options) {
|
|
393
|
+
const url = options.url || "";
|
|
394
|
+
const queryName = options.queryName || url;
|
|
395
|
+
if (!queryName) {
|
|
396
|
+
throw new Error(`Either queryName or url must be specified.`);
|
|
397
|
+
}
|
|
398
|
+
const inflightQueries = /* @__PURE__ */ new Map();
|
|
399
|
+
const mountedKeys = /* @__PURE__ */ new Map();
|
|
400
|
+
let queryFn;
|
|
401
|
+
if (options.queryFn) {
|
|
402
|
+
queryFn = options.queryFn;
|
|
403
|
+
} else if (url) {
|
|
404
|
+
const fetcher = http.use(retries());
|
|
405
|
+
queryFn = async (...args) => {
|
|
406
|
+
let params = "";
|
|
407
|
+
const firstArg = args?.[0];
|
|
408
|
+
if (firstArg) {
|
|
409
|
+
if (typeof firstArg === "string") {
|
|
410
|
+
params = firstArg;
|
|
411
|
+
} else if (typeof firstArg === "object") {
|
|
412
|
+
const entries = [];
|
|
413
|
+
for (const [k, v] of Object.entries(firstArg)) {
|
|
414
|
+
if (v === void 0) continue;
|
|
415
|
+
if (Array.isArray(v)) {
|
|
416
|
+
for (const item of v) {
|
|
417
|
+
if (item === void 0) continue;
|
|
418
|
+
entries.push([k, String(item)]);
|
|
419
|
+
}
|
|
420
|
+
} else {
|
|
421
|
+
entries.push([k, String(v)]);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
params = new URLSearchParams(entries).toString();
|
|
425
|
+
}
|
|
426
|
+
if (params) {
|
|
427
|
+
if (url.includes("?")) {
|
|
428
|
+
params = "&" + params;
|
|
429
|
+
} else {
|
|
430
|
+
params = "?" + params;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
const response = await fetcher.get(url + params);
|
|
435
|
+
return await response.json();
|
|
436
|
+
};
|
|
437
|
+
} else {
|
|
438
|
+
throw new Error(`Either queryFn or url must be specified`);
|
|
439
|
+
}
|
|
440
|
+
const refetchFn = options.refetchFn;
|
|
441
|
+
const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;
|
|
442
|
+
const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;
|
|
443
|
+
const refetchOnStale = options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;
|
|
444
|
+
const store = options.store;
|
|
445
|
+
if (store) {
|
|
446
|
+
if ("persistTo" in store && store.isValid) {
|
|
447
|
+
const isValid = store.isValid;
|
|
448
|
+
options = {
|
|
449
|
+
...options,
|
|
450
|
+
store: {
|
|
451
|
+
...store,
|
|
452
|
+
isValid: (u) => {
|
|
453
|
+
if (!u || typeof u !== "object") {
|
|
454
|
+
return false;
|
|
455
|
+
}
|
|
456
|
+
for (const v of Object.values(u)) {
|
|
457
|
+
if (!v || typeof v !== "object" || !("data" in v) || !("dataUpdatedMs" in v) || !("lastUpdatedMs" in v) || typeof v.dataUpdatedMs !== "number" || typeof v.lastUpdatedMs !== "number" || !isValid(v.data)) {
|
|
458
|
+
return false;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
return true;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
} else {
|
|
467
|
+
const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;
|
|
468
|
+
if (persistTo) {
|
|
469
|
+
options = {
|
|
470
|
+
...options,
|
|
471
|
+
store: {
|
|
472
|
+
persistTo,
|
|
473
|
+
key: queryName,
|
|
474
|
+
expiryMs
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;
|
|
480
|
+
const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;
|
|
481
|
+
const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);
|
|
482
|
+
const log = options?.log ?? SharedQueryConfig.log;
|
|
483
|
+
const queryState = sharedState(
|
|
484
|
+
{},
|
|
485
|
+
// defaultValue
|
|
486
|
+
options
|
|
487
|
+
);
|
|
488
|
+
function isStale(dataUpdatedMs) {
|
|
489
|
+
if (staleMs === 0) return true;
|
|
490
|
+
const ageMs = Date.now() - dataUpdatedMs;
|
|
491
|
+
return ageMs > staleMs;
|
|
492
|
+
}
|
|
493
|
+
function isExpired(dataUpdatedMs) {
|
|
494
|
+
if (expiryMs === 0) return false;
|
|
495
|
+
const ageMs = Date.now() - dataUpdatedMs;
|
|
496
|
+
return ageMs > expiryMs;
|
|
497
|
+
}
|
|
498
|
+
function enforceSizeLimit() {
|
|
499
|
+
if (!maxSize && !maxBytes) {
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
const oldState = queryState.getSnapshot();
|
|
503
|
+
const oldSize = Object.keys(oldState).length;
|
|
504
|
+
if (oldSize <= 1) {
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
const oldByteSize = getByteSize(oldState);
|
|
508
|
+
let numToCut = maxSize ? oldSize - maxSize : 0;
|
|
509
|
+
let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
|
|
510
|
+
if (numToCut <= 0 && bytesToCut <= 0) {
|
|
511
|
+
log(
|
|
512
|
+
`No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
|
|
513
|
+
);
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
log(
|
|
517
|
+
`Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`
|
|
518
|
+
);
|
|
519
|
+
const newState = { ...oldState };
|
|
520
|
+
let needUpdate = false;
|
|
521
|
+
const deleteKeyIfNotMounted = (key, expired) => {
|
|
522
|
+
if (mountedKeys.has(key)) {
|
|
523
|
+
log(`Cannot clean up ${key} as it is mounted`);
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
const byteSize = getByteSize(key) + getByteSize(newState[key]);
|
|
527
|
+
log(
|
|
528
|
+
`Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
|
|
529
|
+
);
|
|
530
|
+
numToCut--;
|
|
531
|
+
bytesToCut -= byteSize;
|
|
532
|
+
delete newState[key];
|
|
533
|
+
needUpdate = true;
|
|
534
|
+
};
|
|
535
|
+
let entriesByTimeAscending = Object.entries(newState).sort(
|
|
536
|
+
(entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
|
|
537
|
+
);
|
|
538
|
+
for (const [key] of entriesByTimeAscending) {
|
|
539
|
+
if (!isExpired(newState[key].lastUpdatedMs)) {
|
|
540
|
+
break;
|
|
541
|
+
}
|
|
542
|
+
deleteKeyIfNotMounted(key, true);
|
|
543
|
+
}
|
|
544
|
+
if (numToCut > 0 || bytesToCut > 0) {
|
|
545
|
+
if (needUpdate) {
|
|
546
|
+
entriesByTimeAscending = Object.entries(newState).sort(
|
|
547
|
+
(entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
for (const [key] of entriesByTimeAscending) {
|
|
551
|
+
deleteKeyIfNotMounted(key, false);
|
|
552
|
+
if (numToCut <= 0 && bytesToCut <= 0) {
|
|
553
|
+
break;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
if (!needUpdate) {
|
|
558
|
+
log(
|
|
559
|
+
`No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
|
|
560
|
+
);
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
queryState.setValue(newState);
|
|
564
|
+
log(
|
|
565
|
+
`Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
function setData(queryKey, data, dataUpdatedMs = Date.now()) {
|
|
569
|
+
const entry = {
|
|
570
|
+
lastUpdatedMs: Date.now(),
|
|
571
|
+
loading: false,
|
|
572
|
+
data,
|
|
573
|
+
dataUpdatedMs
|
|
574
|
+
};
|
|
575
|
+
queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));
|
|
576
|
+
enforceSizeLimit();
|
|
577
|
+
}
|
|
578
|
+
async function startFetching(queryKey, queryType, args) {
|
|
579
|
+
log(`Start fetching ${queryKey}, queryType=${queryType}`);
|
|
580
|
+
try {
|
|
581
|
+
const data = await (queryType === "refetch" && refetchFn ? refetchFn(...args) : queryFn(...args));
|
|
582
|
+
log(`Successfully fetched ${queryKey}`);
|
|
583
|
+
setData(queryKey, data, Date.now());
|
|
584
|
+
return data;
|
|
585
|
+
} catch (e) {
|
|
586
|
+
log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);
|
|
587
|
+
throw e;
|
|
588
|
+
} finally {
|
|
589
|
+
inflightQueries.delete(queryKey);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
function dedupedFetch(queryKey, queryType, ...args) {
|
|
593
|
+
const inflightQuery = inflightQueries.get(queryKey);
|
|
594
|
+
if (inflightQuery) {
|
|
595
|
+
log(
|
|
596
|
+
`Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`
|
|
597
|
+
);
|
|
598
|
+
return inflightQuery.promise;
|
|
599
|
+
}
|
|
600
|
+
const promise = startFetching(queryKey, queryType, args);
|
|
601
|
+
const abortController = new AbortController();
|
|
602
|
+
inflightQueries.set(queryKey, { promise, abortController });
|
|
603
|
+
return promise;
|
|
604
|
+
}
|
|
605
|
+
const obj = {
|
|
606
|
+
queryName,
|
|
607
|
+
queryFn,
|
|
608
|
+
refetchFn,
|
|
609
|
+
expiryMs,
|
|
610
|
+
staleMs,
|
|
611
|
+
refetchOnStale,
|
|
612
|
+
maxSize,
|
|
613
|
+
maxBytes,
|
|
614
|
+
keepLastNonEmptyData,
|
|
615
|
+
log,
|
|
616
|
+
queryState,
|
|
617
|
+
/** Returns a key to identify requests based on the given args. */
|
|
618
|
+
getQueryKey(args) {
|
|
619
|
+
let s = stringifyDeterministicForKeys(args);
|
|
620
|
+
if (s.length > 30) {
|
|
621
|
+
s = XXH.h32(s, 39406).toString(16).slice(2);
|
|
622
|
+
}
|
|
623
|
+
return queryName + ":" + s;
|
|
624
|
+
},
|
|
625
|
+
/**
|
|
626
|
+
* Get the AbortController to abort the inflight query (if any).
|
|
627
|
+
*
|
|
628
|
+
* Note that once you get the controller, you can also get the signal easily
|
|
629
|
+
* using `controller.signal`. So if you need both the controller and the
|
|
630
|
+
* signal, just use this function.
|
|
631
|
+
*/
|
|
632
|
+
getAbortController(args) {
|
|
633
|
+
const queryKey = obj.getQueryKey(args);
|
|
634
|
+
return obj.getAbortControllerByKey(queryKey);
|
|
635
|
+
},
|
|
636
|
+
getAbortControllerByKey(queryKey) {
|
|
637
|
+
return inflightQueries.get(queryKey)?.abortController ?? null;
|
|
638
|
+
},
|
|
639
|
+
/**
|
|
640
|
+
* Get the AbortSignal to check for query abortions.
|
|
641
|
+
*
|
|
642
|
+
* Example using fetch:
|
|
643
|
+
* ```
|
|
644
|
+
* const getUserQuery = sharedQuery({
|
|
645
|
+
* queryName: "getUser",
|
|
646
|
+
* queryFn: (userId: string) => {
|
|
647
|
+
* // Get the signal for this current execution.
|
|
648
|
+
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
649
|
+
*
|
|
650
|
+
* // Pass the signal to fetch so that it can be aborted.
|
|
651
|
+
* const response = await fetch(`/users/${userId}`, { signal });
|
|
652
|
+
*
|
|
653
|
+
* // Check for errors.
|
|
654
|
+
* if (!response.ok) {
|
|
655
|
+
* throw new Error(response.statusText);
|
|
656
|
+
* }
|
|
657
|
+
*
|
|
658
|
+
* // Return the data.
|
|
659
|
+
* return await response.json();
|
|
660
|
+
* },
|
|
661
|
+
* });
|
|
662
|
+
* ```
|
|
663
|
+
*
|
|
664
|
+
* Example using `http.ts`:
|
|
665
|
+
* ```
|
|
666
|
+
* const getUserQuery = sharedQuery({
|
|
667
|
+
* queryName: "getUser",
|
|
668
|
+
* queryFn: (userId: string) => {
|
|
669
|
+
* // Get the signal for this current execution.
|
|
670
|
+
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
671
|
+
*
|
|
672
|
+
* // Pass the signal to fetch so that it can be aborted.
|
|
673
|
+
* const response = await http.get(`/users/${userId}`, { signal });
|
|
674
|
+
* return await response.json();
|
|
675
|
+
* },
|
|
676
|
+
* });
|
|
677
|
+
* ```
|
|
678
|
+
*/
|
|
679
|
+
getAbortSignal(args) {
|
|
680
|
+
const queryKey = obj.getQueryKey(args);
|
|
681
|
+
return obj.getAbortSignalByKey(queryKey);
|
|
682
|
+
},
|
|
683
|
+
getAbortSignalByKey(queryKey) {
|
|
684
|
+
return obj.getAbortControllerByKey(queryKey)?.signal ?? null;
|
|
685
|
+
},
|
|
686
|
+
/** For cached data, we need to return the correct timestamps as well. */
|
|
687
|
+
async getCachedOrFetch(...args) {
|
|
688
|
+
const startMs = Date.now();
|
|
689
|
+
await queryState.readyPromise;
|
|
690
|
+
const waitedMs = Date.now() - startMs;
|
|
691
|
+
const queryKey = obj.getQueryKey(args);
|
|
692
|
+
const cached = queryState.getSnapshot()?.[queryKey];
|
|
693
|
+
if (waitedMs) {
|
|
694
|
+
log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
|
|
695
|
+
}
|
|
696
|
+
if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {
|
|
697
|
+
if (!isStale(cached.dataUpdatedMs ?? 0)) {
|
|
698
|
+
log(`Return fresh data ${queryKey} from cache without fetching`);
|
|
699
|
+
return cached;
|
|
700
|
+
}
|
|
701
|
+
if (refetchOnStale) {
|
|
702
|
+
log(`refetchOnStale for ${queryKey}`);
|
|
703
|
+
void dedupedFetch(queryKey, "query", ...args);
|
|
704
|
+
}
|
|
705
|
+
log(`Returning stale data for ${queryKey}`);
|
|
706
|
+
return cached;
|
|
707
|
+
}
|
|
708
|
+
const data = await dedupedFetch(queryKey, "query", ...args);
|
|
709
|
+
const now = Date.now();
|
|
710
|
+
return {
|
|
711
|
+
// Don't keep old error.
|
|
712
|
+
lastUpdatedMs: now,
|
|
713
|
+
loading: false,
|
|
714
|
+
data,
|
|
715
|
+
dataUpdatedMs: now
|
|
716
|
+
};
|
|
717
|
+
},
|
|
718
|
+
/** Get the entire stored entry for a query key. */
|
|
719
|
+
getQueryValue(queryKey) {
|
|
720
|
+
return queryState.getSnapshot()?.[queryKey];
|
|
721
|
+
},
|
|
722
|
+
/** Get the current stored data for a query key. */
|
|
723
|
+
getData(queryKey) {
|
|
724
|
+
const stateValue = queryState.getSnapshot()?.[queryKey];
|
|
725
|
+
if (stateValue?.lastUpdatedMs) {
|
|
726
|
+
if (isExpired(stateValue.lastUpdatedMs)) {
|
|
727
|
+
obj.deleteData(queryKey);
|
|
728
|
+
return void 0;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
return stateValue?.data;
|
|
732
|
+
},
|
|
733
|
+
/** Set the data directly if the user obtained it from somewhere else. */
|
|
734
|
+
setData,
|
|
735
|
+
/**
|
|
736
|
+
* Do a new fetch even when the data is already cached, but don't fetch if
|
|
737
|
+
* another fetch is already inflight.
|
|
738
|
+
*/
|
|
739
|
+
async updateFromSource(...args) {
|
|
740
|
+
const key = obj.getQueryKey(args);
|
|
741
|
+
return await dedupedFetch(key, "query", ...args);
|
|
742
|
+
},
|
|
743
|
+
/**
|
|
744
|
+
* Perform an explicit refetch. If `options.refetchFn` was not specified,
|
|
745
|
+
* then this would be identical to calling `obj.updateFromSource()`.
|
|
746
|
+
*/
|
|
747
|
+
async refetch(...args) {
|
|
748
|
+
const key = obj.getQueryKey(args);
|
|
749
|
+
return await dedupedFetch(key, "refetch", ...args);
|
|
750
|
+
},
|
|
751
|
+
/** Delete the cached data for one set of arguments. */
|
|
752
|
+
deleteData(queryKey) {
|
|
753
|
+
const record = queryState.getSnapshot();
|
|
754
|
+
const clone = { ...record };
|
|
755
|
+
delete clone[queryKey];
|
|
756
|
+
queryState.setValue(clone);
|
|
757
|
+
const inflight = inflightQueries.get(queryKey);
|
|
758
|
+
if (inflight) {
|
|
759
|
+
inflightQueries.delete(queryKey);
|
|
760
|
+
inflight.abortController.abort("Deleted");
|
|
761
|
+
}
|
|
762
|
+
},
|
|
763
|
+
/** Delete all currently cached data & all inflight promises. */
|
|
764
|
+
clear() {
|
|
765
|
+
queryState.delete();
|
|
766
|
+
for (const { abortController } of Array.from(inflightQueries.values())) {
|
|
767
|
+
abortController.abort("Cleared");
|
|
768
|
+
}
|
|
769
|
+
inflightQueries.clear();
|
|
770
|
+
},
|
|
771
|
+
/** Keep track of mounted keys. */
|
|
772
|
+
mount(queryKey) {
|
|
773
|
+
mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);
|
|
774
|
+
},
|
|
775
|
+
/** Clean up mounted keys. */
|
|
776
|
+
unmount(queryKey) {
|
|
777
|
+
const count = mountedKeys.get(queryKey);
|
|
778
|
+
if (count === 1) {
|
|
779
|
+
mountedKeys.delete(queryKey);
|
|
780
|
+
} else {
|
|
781
|
+
mountedKeys.set(queryKey, (count ?? 0) - 1);
|
|
782
|
+
}
|
|
783
|
+
},
|
|
784
|
+
/**
|
|
785
|
+
* Discard the oldest entries if the size exceeds the limit. The last
|
|
786
|
+
* remaining record cannot be deleted no matter what the limit is.
|
|
787
|
+
*/
|
|
788
|
+
enforceSizeLimit
|
|
789
|
+
};
|
|
790
|
+
return obj;
|
|
791
|
+
}
|
|
792
|
+
function sharedQuery(options) {
|
|
793
|
+
return sharedQuery1(options);
|
|
794
|
+
}
|
|
795
|
+
var DEFAULT_QUERY_STATE_ENTRY = {
|
|
796
|
+
lastUpdatedMs: 0,
|
|
797
|
+
loading: true
|
|
798
|
+
};
|
|
799
|
+
function useSharedQuery(query, ...args) {
|
|
800
|
+
const stableArgs = useDeepMemo(args);
|
|
801
|
+
const [queryState, setQueryState] = useSharedState(query.queryState);
|
|
802
|
+
const isMounted = useRef(true);
|
|
803
|
+
const queryKey = useMemo2(
|
|
804
|
+
() => query.getQueryKey(stableArgs),
|
|
805
|
+
[query, stableArgs]
|
|
806
|
+
);
|
|
807
|
+
const queryStateValue = queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;
|
|
808
|
+
const setQueryStateValue = useCallback(
|
|
809
|
+
(next) => {
|
|
810
|
+
setQueryState((prev) => {
|
|
811
|
+
const clone = { ...prev };
|
|
812
|
+
clone[queryKey] = typeof next === "function" ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY) : next;
|
|
813
|
+
return clone;
|
|
814
|
+
});
|
|
815
|
+
},
|
|
816
|
+
[queryKey, setQueryState]
|
|
817
|
+
);
|
|
818
|
+
const [lastNonEmptyData, setLastNonEmptyData] = useState2();
|
|
819
|
+
useEffect(() => {
|
|
820
|
+
if (query.keepLastNonEmptyData && queryStateValue.data !== void 0) {
|
|
821
|
+
setLastNonEmptyData(queryStateValue.data);
|
|
822
|
+
}
|
|
823
|
+
}, [query.keepLastNonEmptyData, queryStateValue.data]);
|
|
824
|
+
const executeQuery = useCallback(
|
|
825
|
+
async (isRefetch) => {
|
|
826
|
+
query.log(
|
|
827
|
+
`Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
|
|
828
|
+
);
|
|
829
|
+
if (!isMounted.current) return;
|
|
830
|
+
setQueryStateValue((prev) => ({
|
|
831
|
+
// Keep old data and error.
|
|
832
|
+
...prev,
|
|
833
|
+
lastUpdatedMs: Date.now(),
|
|
834
|
+
loading: true
|
|
835
|
+
}));
|
|
836
|
+
try {
|
|
837
|
+
let state;
|
|
838
|
+
if (isRefetch) {
|
|
839
|
+
const data = await query.refetch(...stableArgs);
|
|
840
|
+
const now = Date.now();
|
|
841
|
+
state = {
|
|
842
|
+
// Don't keep old error.
|
|
843
|
+
lastUpdatedMs: now,
|
|
844
|
+
loading: false,
|
|
845
|
+
data,
|
|
846
|
+
dataUpdatedMs: now
|
|
847
|
+
};
|
|
848
|
+
} else {
|
|
849
|
+
state = await query.getCachedOrFetch(...stableArgs);
|
|
850
|
+
}
|
|
851
|
+
if (!isMounted.current) return;
|
|
852
|
+
setQueryStateValue({ ...state, loading: false });
|
|
853
|
+
return state.data;
|
|
854
|
+
} catch (e) {
|
|
855
|
+
if (!isMounted.current) return;
|
|
856
|
+
const now = Date.now();
|
|
857
|
+
setQueryStateValue((prev) => ({
|
|
858
|
+
// Keep old data.
|
|
859
|
+
...prev,
|
|
860
|
+
lastUpdatedMs: now,
|
|
861
|
+
loading: false,
|
|
862
|
+
error: e,
|
|
863
|
+
errorUpdatedMs: now
|
|
864
|
+
}));
|
|
865
|
+
}
|
|
866
|
+
},
|
|
867
|
+
[query, queryKey, setQueryStateValue, stableArgs]
|
|
868
|
+
);
|
|
869
|
+
useEffect(() => {
|
|
870
|
+
isMounted.current = true;
|
|
871
|
+
query.mount(queryKey);
|
|
872
|
+
void executeQuery(false);
|
|
873
|
+
return () => {
|
|
874
|
+
isMounted.current = false;
|
|
875
|
+
query.unmount(queryKey);
|
|
876
|
+
};
|
|
877
|
+
}, [executeQuery, query, queryKey]);
|
|
878
|
+
return useMemo2(() => {
|
|
879
|
+
return {
|
|
880
|
+
...queryStateValue,
|
|
881
|
+
// Fill with lastNonEmptyData when data is undefined.
|
|
882
|
+
data: queryStateValue.data !== void 0 ? queryStateValue.data : lastNonEmptyData,
|
|
883
|
+
latestData: queryStateValue.data,
|
|
884
|
+
// This works only if the user-given queryFn supports abort. If not,
|
|
885
|
+
// this function doesn't do anything, since we don't have any means to
|
|
886
|
+
// abort the running queryFn.
|
|
887
|
+
abortCurrentQuery: (reason) => {
|
|
888
|
+
const controller = query.getAbortControllerByKey(queryKey);
|
|
889
|
+
controller?.abort(reason);
|
|
890
|
+
return Boolean(controller);
|
|
891
|
+
},
|
|
892
|
+
getCachedOrFetch: async () => {
|
|
893
|
+
const data = await query.getCachedOrFetch(...stableArgs);
|
|
894
|
+
return nonNil(
|
|
895
|
+
data.data,
|
|
896
|
+
typeof data.error === "string" ? data.error : JSON.stringify(data.error)
|
|
897
|
+
);
|
|
898
|
+
},
|
|
899
|
+
refetch: () => {
|
|
900
|
+
return executeQuery(true);
|
|
901
|
+
},
|
|
902
|
+
setData: (data, dataUpdatedMs) => {
|
|
903
|
+
query.setData(queryKey, data, dataUpdatedMs);
|
|
904
|
+
},
|
|
905
|
+
deleteData: () => {
|
|
906
|
+
query.deleteData(queryKey);
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
}, [
|
|
910
|
+
executeQuery,
|
|
911
|
+
lastNonEmptyData,
|
|
912
|
+
query,
|
|
913
|
+
queryKey,
|
|
914
|
+
queryStateValue,
|
|
915
|
+
stableArgs
|
|
916
|
+
]);
|
|
917
|
+
}
|
|
27
918
|
export {
|
|
28
919
|
SharedQueryConfig,
|
|
29
920
|
SharedStateConfig,
|