@choksheak/react-utils 0.4.4 → 0.4.6
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 +985 -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 +922 -25
- package/package.json +1 -41
- package/sharedQuery.cjs +944 -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 +912 -10
- package/sharedState.cjs +334 -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 +299 -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/chunk-FXCYHS3L.mjs
DELETED
|
@@ -1,577 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
sharedState,
|
|
3
|
-
useSharedState
|
|
4
|
-
} from "./chunk-YHU4KW2D.mjs";
|
|
5
|
-
import {
|
|
6
|
-
stringifyDeterministicForKeys
|
|
7
|
-
} from "./chunk-4235I4VO.mjs";
|
|
8
|
-
import {
|
|
9
|
-
useDeepMemo
|
|
10
|
-
} from "./chunk-4J7TN5JN.mjs";
|
|
11
|
-
|
|
12
|
-
// src/sharedQuery.ts
|
|
13
|
-
import { http, retries } from "@choksheak/ts-utils/http";
|
|
14
|
-
import { nonNil } from "@choksheak/ts-utils/nonNil";
|
|
15
|
-
import getByteSize from "object-sizeof";
|
|
16
|
-
import {
|
|
17
|
-
useCallback,
|
|
18
|
-
useEffect,
|
|
19
|
-
useMemo,
|
|
20
|
-
useRef,
|
|
21
|
-
useState
|
|
22
|
-
} from "react";
|
|
23
|
-
import XXH from "xxhashjs";
|
|
24
|
-
var SharedQueryConfig = {
|
|
25
|
-
/** Refetch on every page load. */
|
|
26
|
-
staleMs: 0,
|
|
27
|
-
/** Keep in cache for a long time. */
|
|
28
|
-
expiryMs: 30 * 864e5,
|
|
29
|
-
/** Always refetch automatically if the data is stale. */
|
|
30
|
-
refetchOnStale: true,
|
|
31
|
-
/** No default persistence configured. */
|
|
32
|
-
persistTo: void 0,
|
|
33
|
-
/** 100 is not too large, but please tweak accordingly. */
|
|
34
|
-
maxSize: 100,
|
|
35
|
-
/** 100kb limit before discarding old records. */
|
|
36
|
-
maxBytes: 1e5,
|
|
37
|
-
/** Default to log to console. */
|
|
38
|
-
log: (...args) => console.log("[sharedQuery]", ...args)
|
|
39
|
-
};
|
|
40
|
-
function configureSharedQuery(config) {
|
|
41
|
-
Object.assign(SharedQueryConfig, config);
|
|
42
|
-
}
|
|
43
|
-
var seenQueryNames = /* @__PURE__ */ new Set();
|
|
44
|
-
function sharedQuery(options) {
|
|
45
|
-
const url = options.url || "";
|
|
46
|
-
const queryName = options.queryName || url;
|
|
47
|
-
if (!queryName) {
|
|
48
|
-
throw new Error(`Either queryName or url must be specified.`);
|
|
49
|
-
}
|
|
50
|
-
if (seenQueryNames.has(queryName)) {
|
|
51
|
-
console.warn(`Duplicate shared query name "${queryName}"`);
|
|
52
|
-
}
|
|
53
|
-
seenQueryNames.add(queryName);
|
|
54
|
-
const inflightQueries = /* @__PURE__ */ new Map();
|
|
55
|
-
const mountedKeys = /* @__PURE__ */ new Map();
|
|
56
|
-
let queryFn;
|
|
57
|
-
if (options.queryFn) {
|
|
58
|
-
queryFn = options.queryFn;
|
|
59
|
-
} else if (url) {
|
|
60
|
-
const fetcher = http.use(retries());
|
|
61
|
-
queryFn = async (...args) => {
|
|
62
|
-
let params = "";
|
|
63
|
-
const firstArg = args?.[0];
|
|
64
|
-
if (firstArg) {
|
|
65
|
-
if (typeof firstArg === "string") {
|
|
66
|
-
params = firstArg;
|
|
67
|
-
} else if (typeof firstArg === "object") {
|
|
68
|
-
const entries = [];
|
|
69
|
-
for (const [k, v] of Object.entries(firstArg)) {
|
|
70
|
-
if (v === void 0) continue;
|
|
71
|
-
if (Array.isArray(v)) {
|
|
72
|
-
for (const item of v) {
|
|
73
|
-
if (item === void 0) continue;
|
|
74
|
-
entries.push([k, String(item)]);
|
|
75
|
-
}
|
|
76
|
-
} else {
|
|
77
|
-
entries.push([k, String(v)]);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
params = new URLSearchParams(entries).toString();
|
|
81
|
-
}
|
|
82
|
-
if (params) {
|
|
83
|
-
if (url.includes("?")) {
|
|
84
|
-
params = "&" + params;
|
|
85
|
-
} else {
|
|
86
|
-
params = "?" + params;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
const response = await fetcher.get(url + params);
|
|
91
|
-
return await response.json();
|
|
92
|
-
};
|
|
93
|
-
} else {
|
|
94
|
-
throw new Error(`Either queryFn or url must be specified`);
|
|
95
|
-
}
|
|
96
|
-
const refetchFn = options.refetchFn;
|
|
97
|
-
const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;
|
|
98
|
-
const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;
|
|
99
|
-
const refetchOnStale = options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;
|
|
100
|
-
const store = options.store;
|
|
101
|
-
if (store) {
|
|
102
|
-
if ("persistTo" in store && store.isValid) {
|
|
103
|
-
const isValid = store.isValid;
|
|
104
|
-
options = {
|
|
105
|
-
...options,
|
|
106
|
-
store: {
|
|
107
|
-
...store,
|
|
108
|
-
isValid: (u) => {
|
|
109
|
-
if (!u || typeof u !== "object") {
|
|
110
|
-
return false;
|
|
111
|
-
}
|
|
112
|
-
for (const v of Object.values(u)) {
|
|
113
|
-
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)) {
|
|
114
|
-
return false;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
return true;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
} else {
|
|
123
|
-
const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;
|
|
124
|
-
if (persistTo) {
|
|
125
|
-
options = {
|
|
126
|
-
...options,
|
|
127
|
-
store: {
|
|
128
|
-
persistTo,
|
|
129
|
-
key: queryName,
|
|
130
|
-
expiryMs
|
|
131
|
-
}
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;
|
|
136
|
-
const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;
|
|
137
|
-
const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);
|
|
138
|
-
const log = options?.log ?? SharedQueryConfig.log;
|
|
139
|
-
const queryState = sharedState(
|
|
140
|
-
{},
|
|
141
|
-
// defaultValue
|
|
142
|
-
options
|
|
143
|
-
);
|
|
144
|
-
function isStale(dataUpdatedMs) {
|
|
145
|
-
if (staleMs === 0) return true;
|
|
146
|
-
const ageMs = Date.now() - dataUpdatedMs;
|
|
147
|
-
return ageMs > staleMs;
|
|
148
|
-
}
|
|
149
|
-
function isExpired(dataUpdatedMs) {
|
|
150
|
-
if (expiryMs === 0) return false;
|
|
151
|
-
const ageMs = Date.now() - dataUpdatedMs;
|
|
152
|
-
return ageMs > expiryMs;
|
|
153
|
-
}
|
|
154
|
-
function enforceSizeLimit() {
|
|
155
|
-
if (!maxSize && !maxBytes) {
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
const oldState = queryState.getSnapshot();
|
|
159
|
-
const oldSize = Object.keys(oldState).length;
|
|
160
|
-
if (oldSize <= 1) {
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
const oldByteSize = getByteSize(oldState);
|
|
164
|
-
let numToCut = maxSize ? oldSize - maxSize : 0;
|
|
165
|
-
let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
|
|
166
|
-
if (numToCut <= 0 && bytesToCut <= 0) {
|
|
167
|
-
log(
|
|
168
|
-
`No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
|
|
169
|
-
);
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
log(
|
|
173
|
-
`Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`
|
|
174
|
-
);
|
|
175
|
-
const newState = { ...oldState };
|
|
176
|
-
let needUpdate = false;
|
|
177
|
-
const deleteKeyIfNotMounted = (key, expired) => {
|
|
178
|
-
if (mountedKeys.has(key)) {
|
|
179
|
-
log(`Cannot clean up ${key} as it is mounted`);
|
|
180
|
-
return;
|
|
181
|
-
}
|
|
182
|
-
const byteSize = getByteSize(key) + getByteSize(newState[key]);
|
|
183
|
-
log(
|
|
184
|
-
`Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
|
|
185
|
-
);
|
|
186
|
-
numToCut--;
|
|
187
|
-
bytesToCut -= byteSize;
|
|
188
|
-
delete newState[key];
|
|
189
|
-
needUpdate = true;
|
|
190
|
-
};
|
|
191
|
-
let entriesByTimeAscending = Object.entries(newState).sort(
|
|
192
|
-
(entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
|
|
193
|
-
);
|
|
194
|
-
for (const [key] of entriesByTimeAscending) {
|
|
195
|
-
if (!isExpired(newState[key].lastUpdatedMs)) {
|
|
196
|
-
break;
|
|
197
|
-
}
|
|
198
|
-
deleteKeyIfNotMounted(key, true);
|
|
199
|
-
}
|
|
200
|
-
if (numToCut > 0 || bytesToCut > 0) {
|
|
201
|
-
if (needUpdate) {
|
|
202
|
-
entriesByTimeAscending = Object.entries(newState).sort(
|
|
203
|
-
(entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
|
|
204
|
-
);
|
|
205
|
-
}
|
|
206
|
-
for (const [key] of entriesByTimeAscending) {
|
|
207
|
-
deleteKeyIfNotMounted(key, false);
|
|
208
|
-
if (numToCut <= 0 && bytesToCut <= 0) {
|
|
209
|
-
break;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
if (!needUpdate) {
|
|
214
|
-
log(
|
|
215
|
-
`No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
|
|
216
|
-
);
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
queryState.setValue(newState);
|
|
220
|
-
log(
|
|
221
|
-
`Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
|
-
function setData(queryKey, data, dataUpdatedMs = Date.now()) {
|
|
225
|
-
const entry = {
|
|
226
|
-
lastUpdatedMs: Date.now(),
|
|
227
|
-
loading: false,
|
|
228
|
-
data,
|
|
229
|
-
dataUpdatedMs
|
|
230
|
-
};
|
|
231
|
-
queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));
|
|
232
|
-
enforceSizeLimit();
|
|
233
|
-
}
|
|
234
|
-
async function startFetching(queryKey, queryType, args) {
|
|
235
|
-
log(`Start fetching ${queryKey}, queryType=${queryType}`);
|
|
236
|
-
try {
|
|
237
|
-
const data = await (queryType === "refetch" && refetchFn ? refetchFn(...args) : queryFn(...args));
|
|
238
|
-
log(`Successfully fetched ${queryKey}`);
|
|
239
|
-
setData(queryKey, data, Date.now());
|
|
240
|
-
return data;
|
|
241
|
-
} catch (e) {
|
|
242
|
-
log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);
|
|
243
|
-
throw e;
|
|
244
|
-
} finally {
|
|
245
|
-
inflightQueries.delete(queryKey);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
function dedupedFetch(queryKey, queryType, ...args) {
|
|
249
|
-
const inflightQuery = inflightQueries.get(queryKey);
|
|
250
|
-
if (inflightQuery) {
|
|
251
|
-
log(
|
|
252
|
-
`Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`
|
|
253
|
-
);
|
|
254
|
-
return inflightQuery.promise;
|
|
255
|
-
}
|
|
256
|
-
const promise = startFetching(queryKey, queryType, args);
|
|
257
|
-
const abortController = new AbortController();
|
|
258
|
-
inflightQueries.set(queryKey, { promise, abortController });
|
|
259
|
-
return promise;
|
|
260
|
-
}
|
|
261
|
-
const obj = {
|
|
262
|
-
queryName,
|
|
263
|
-
queryFn,
|
|
264
|
-
refetchFn,
|
|
265
|
-
expiryMs,
|
|
266
|
-
staleMs,
|
|
267
|
-
refetchOnStale,
|
|
268
|
-
maxSize,
|
|
269
|
-
maxBytes,
|
|
270
|
-
keepLastNonEmptyData,
|
|
271
|
-
log,
|
|
272
|
-
queryState,
|
|
273
|
-
/** Returns a key to identify requests based on the given args. */
|
|
274
|
-
getQueryKey(args) {
|
|
275
|
-
let s = stringifyDeterministicForKeys(args);
|
|
276
|
-
if (s.length > 30) {
|
|
277
|
-
s = XXH.h32(s, 39406).toString(16).slice(2);
|
|
278
|
-
}
|
|
279
|
-
return queryName + ":" + s;
|
|
280
|
-
},
|
|
281
|
-
/**
|
|
282
|
-
* Get the AbortController to abort the inflight query (if any).
|
|
283
|
-
*
|
|
284
|
-
* Note that once you get the controller, you can also get the signal easily
|
|
285
|
-
* using `controller.signal`. So if you need both the controller and the
|
|
286
|
-
* signal, just use this function.
|
|
287
|
-
*/
|
|
288
|
-
getAbortController(args) {
|
|
289
|
-
const queryKey = obj.getQueryKey(args);
|
|
290
|
-
return obj.getAbortControllerByKey(queryKey);
|
|
291
|
-
},
|
|
292
|
-
getAbortControllerByKey(queryKey) {
|
|
293
|
-
return inflightQueries.get(queryKey)?.abortController ?? null;
|
|
294
|
-
},
|
|
295
|
-
/**
|
|
296
|
-
* Get the AbortSignal to check for query abortions.
|
|
297
|
-
*
|
|
298
|
-
* Example using fetch:
|
|
299
|
-
* ```
|
|
300
|
-
* const getUserQuery = sharedQuery({
|
|
301
|
-
* queryName: "getUser",
|
|
302
|
-
* queryFn: (userId: string) => {
|
|
303
|
-
* // Get the signal for this current execution.
|
|
304
|
-
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
305
|
-
*
|
|
306
|
-
* // Pass the signal to fetch so that it can be aborted.
|
|
307
|
-
* const response = await fetch(`/users/${userId}`, { signal });
|
|
308
|
-
*
|
|
309
|
-
* // Check for errors.
|
|
310
|
-
* if (!response.ok) {
|
|
311
|
-
* throw new Error(response.statusText);
|
|
312
|
-
* }
|
|
313
|
-
*
|
|
314
|
-
* // Return the data.
|
|
315
|
-
* return await response.json();
|
|
316
|
-
* },
|
|
317
|
-
* });
|
|
318
|
-
* ```
|
|
319
|
-
*
|
|
320
|
-
* Example using `http.ts`:
|
|
321
|
-
* ```
|
|
322
|
-
* const getUserQuery = sharedQuery({
|
|
323
|
-
* queryName: "getUser",
|
|
324
|
-
* queryFn: (userId: string) => {
|
|
325
|
-
* // Get the signal for this current execution.
|
|
326
|
-
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
327
|
-
*
|
|
328
|
-
* // Pass the signal to fetch so that it can be aborted.
|
|
329
|
-
* const response = await http.get(`/users/${userId}`, { signal });
|
|
330
|
-
* return await response.json();
|
|
331
|
-
* },
|
|
332
|
-
* });
|
|
333
|
-
* ```
|
|
334
|
-
*/
|
|
335
|
-
getAbortSignal(args) {
|
|
336
|
-
const queryKey = obj.getQueryKey(args);
|
|
337
|
-
return obj.getAbortSignalByKey(queryKey);
|
|
338
|
-
},
|
|
339
|
-
getAbortSignalByKey(queryKey) {
|
|
340
|
-
return obj.getAbortControllerByKey(queryKey)?.signal ?? null;
|
|
341
|
-
},
|
|
342
|
-
/** For cached data, we need to return the correct timestamps as well. */
|
|
343
|
-
async getCachedOrFetch(...args) {
|
|
344
|
-
const startMs = Date.now();
|
|
345
|
-
await queryState.readyPromise;
|
|
346
|
-
const waitedMs = Date.now() - startMs;
|
|
347
|
-
const queryKey = obj.getQueryKey(args);
|
|
348
|
-
const cached = queryState.getSnapshot()?.[queryKey];
|
|
349
|
-
if (waitedMs) {
|
|
350
|
-
log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
|
|
351
|
-
}
|
|
352
|
-
if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {
|
|
353
|
-
if (!isStale(cached.dataUpdatedMs ?? 0)) {
|
|
354
|
-
log(`Return fresh data ${queryKey} from cache without fetching`);
|
|
355
|
-
return cached;
|
|
356
|
-
}
|
|
357
|
-
if (refetchOnStale) {
|
|
358
|
-
log(`refetchOnStale for ${queryKey}`);
|
|
359
|
-
void dedupedFetch(queryKey, "query", ...args);
|
|
360
|
-
}
|
|
361
|
-
log(`Returning stale data for ${queryKey}`);
|
|
362
|
-
return cached;
|
|
363
|
-
}
|
|
364
|
-
const data = await dedupedFetch(queryKey, "query", ...args);
|
|
365
|
-
const now = Date.now();
|
|
366
|
-
return {
|
|
367
|
-
// Don't keep old error.
|
|
368
|
-
lastUpdatedMs: now,
|
|
369
|
-
loading: false,
|
|
370
|
-
data,
|
|
371
|
-
dataUpdatedMs: now
|
|
372
|
-
};
|
|
373
|
-
},
|
|
374
|
-
/** Get the entire stored entry for a query key. */
|
|
375
|
-
getQueryValue(queryKey) {
|
|
376
|
-
return queryState.getSnapshot()?.[queryKey];
|
|
377
|
-
},
|
|
378
|
-
/** Get the current stored data for a query key. */
|
|
379
|
-
getData(queryKey) {
|
|
380
|
-
const stateValue = queryState.getSnapshot()?.[queryKey];
|
|
381
|
-
if (stateValue?.lastUpdatedMs) {
|
|
382
|
-
if (isExpired(stateValue.lastUpdatedMs)) {
|
|
383
|
-
obj.deleteData(queryKey);
|
|
384
|
-
return void 0;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
return stateValue?.data;
|
|
388
|
-
},
|
|
389
|
-
/** Set the data directly if the user obtained it from somewhere else. */
|
|
390
|
-
setData,
|
|
391
|
-
/**
|
|
392
|
-
* Do a new fetch even when the data is already cached, but don't fetch if
|
|
393
|
-
* another fetch is already inflight.
|
|
394
|
-
*/
|
|
395
|
-
async updateFromSource(...args) {
|
|
396
|
-
const key = obj.getQueryKey(args);
|
|
397
|
-
return await dedupedFetch(key, "query", ...args);
|
|
398
|
-
},
|
|
399
|
-
/**
|
|
400
|
-
* Perform an explicit refetch. If `options.refetchFn` was not specified,
|
|
401
|
-
* then this would be identical to calling `obj.updateFromSource()`.
|
|
402
|
-
*/
|
|
403
|
-
async refetch(...args) {
|
|
404
|
-
const key = obj.getQueryKey(args);
|
|
405
|
-
return await dedupedFetch(key, "refetch", ...args);
|
|
406
|
-
},
|
|
407
|
-
/** Delete the cached data for one set of arguments. */
|
|
408
|
-
deleteData(queryKey) {
|
|
409
|
-
const record = queryState.getSnapshot();
|
|
410
|
-
const clone = { ...record };
|
|
411
|
-
delete clone[queryKey];
|
|
412
|
-
queryState.setValue(clone);
|
|
413
|
-
const inflight = inflightQueries.get(queryKey);
|
|
414
|
-
if (inflight) {
|
|
415
|
-
inflightQueries.delete(queryKey);
|
|
416
|
-
inflight.abortController.abort("Deleted");
|
|
417
|
-
}
|
|
418
|
-
},
|
|
419
|
-
/** Delete all currently cached data & all inflight promises. */
|
|
420
|
-
clear() {
|
|
421
|
-
queryState.delete();
|
|
422
|
-
for (const { abortController } of Array.from(inflightQueries.values())) {
|
|
423
|
-
abortController.abort("Cleared");
|
|
424
|
-
}
|
|
425
|
-
inflightQueries.clear();
|
|
426
|
-
},
|
|
427
|
-
/** Keep track of mounted keys. */
|
|
428
|
-
mount(queryKey) {
|
|
429
|
-
mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);
|
|
430
|
-
},
|
|
431
|
-
/** Clean up mounted keys. */
|
|
432
|
-
unmount(queryKey) {
|
|
433
|
-
const count = mountedKeys.get(queryKey);
|
|
434
|
-
if (count === 1) {
|
|
435
|
-
mountedKeys.delete(queryKey);
|
|
436
|
-
} else {
|
|
437
|
-
mountedKeys.set(queryKey, (count ?? 0) - 1);
|
|
438
|
-
}
|
|
439
|
-
},
|
|
440
|
-
/**
|
|
441
|
-
* Discard the oldest entries if the size exceeds the limit. The last
|
|
442
|
-
* remaining record cannot be deleted no matter what the limit is.
|
|
443
|
-
*/
|
|
444
|
-
enforceSizeLimit
|
|
445
|
-
};
|
|
446
|
-
return obj;
|
|
447
|
-
}
|
|
448
|
-
var DEFAULT_QUERY_STATE_ENTRY = {
|
|
449
|
-
lastUpdatedMs: 0,
|
|
450
|
-
loading: true
|
|
451
|
-
};
|
|
452
|
-
function useSharedQuery(query, ...args) {
|
|
453
|
-
const stableArgs = useDeepMemo(args);
|
|
454
|
-
const [queryState, setQueryState] = useSharedState(query.queryState);
|
|
455
|
-
const isMounted = useRef(true);
|
|
456
|
-
const queryKey = useMemo(
|
|
457
|
-
() => query.getQueryKey(stableArgs),
|
|
458
|
-
[query, stableArgs]
|
|
459
|
-
);
|
|
460
|
-
const queryStateValue = queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;
|
|
461
|
-
const setQueryStateValue = useCallback(
|
|
462
|
-
(next) => {
|
|
463
|
-
setQueryState((prev) => {
|
|
464
|
-
const clone = { ...prev };
|
|
465
|
-
clone[queryKey] = typeof next === "function" ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY) : next;
|
|
466
|
-
return clone;
|
|
467
|
-
});
|
|
468
|
-
},
|
|
469
|
-
[queryKey, setQueryState]
|
|
470
|
-
);
|
|
471
|
-
const [lastNonEmptyData, setLastNonEmptyData] = useState();
|
|
472
|
-
useEffect(() => {
|
|
473
|
-
if (query.keepLastNonEmptyData && queryStateValue.data !== void 0) {
|
|
474
|
-
setLastNonEmptyData(queryStateValue.data);
|
|
475
|
-
}
|
|
476
|
-
}, [query.keepLastNonEmptyData, queryStateValue.data]);
|
|
477
|
-
const executeQuery = useCallback(
|
|
478
|
-
async (isRefetch) => {
|
|
479
|
-
query.log(
|
|
480
|
-
`Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
|
|
481
|
-
);
|
|
482
|
-
if (!isMounted.current) return;
|
|
483
|
-
setQueryStateValue((prev) => ({
|
|
484
|
-
// Keep old data and error.
|
|
485
|
-
...prev,
|
|
486
|
-
lastUpdatedMs: Date.now(),
|
|
487
|
-
loading: true
|
|
488
|
-
}));
|
|
489
|
-
try {
|
|
490
|
-
let state;
|
|
491
|
-
if (isRefetch) {
|
|
492
|
-
const data = await query.refetch(...stableArgs);
|
|
493
|
-
const now = Date.now();
|
|
494
|
-
state = {
|
|
495
|
-
// Don't keep old error.
|
|
496
|
-
lastUpdatedMs: now,
|
|
497
|
-
loading: false,
|
|
498
|
-
data,
|
|
499
|
-
dataUpdatedMs: now
|
|
500
|
-
};
|
|
501
|
-
} else {
|
|
502
|
-
state = await query.getCachedOrFetch(...stableArgs);
|
|
503
|
-
}
|
|
504
|
-
if (!isMounted.current) return;
|
|
505
|
-
setQueryStateValue({ ...state, loading: false });
|
|
506
|
-
return state.data;
|
|
507
|
-
} catch (e) {
|
|
508
|
-
if (!isMounted.current) return;
|
|
509
|
-
const now = Date.now();
|
|
510
|
-
setQueryStateValue((prev) => ({
|
|
511
|
-
// Keep old data.
|
|
512
|
-
...prev,
|
|
513
|
-
lastUpdatedMs: now,
|
|
514
|
-
loading: false,
|
|
515
|
-
error: e,
|
|
516
|
-
errorUpdatedMs: now
|
|
517
|
-
}));
|
|
518
|
-
}
|
|
519
|
-
},
|
|
520
|
-
[query, queryKey, setQueryStateValue, stableArgs]
|
|
521
|
-
);
|
|
522
|
-
useEffect(() => {
|
|
523
|
-
isMounted.current = true;
|
|
524
|
-
query.mount(queryKey);
|
|
525
|
-
void executeQuery(false);
|
|
526
|
-
return () => {
|
|
527
|
-
isMounted.current = false;
|
|
528
|
-
query.unmount(queryKey);
|
|
529
|
-
};
|
|
530
|
-
}, [executeQuery, query, queryKey]);
|
|
531
|
-
return useMemo(() => {
|
|
532
|
-
return {
|
|
533
|
-
...queryStateValue,
|
|
534
|
-
// Fill with lastNonEmptyData when data is undefined.
|
|
535
|
-
data: queryStateValue.data !== void 0 ? queryStateValue.data : lastNonEmptyData,
|
|
536
|
-
latestData: queryStateValue.data,
|
|
537
|
-
// This works only if the user-given queryFn supports abort. If not,
|
|
538
|
-
// this function doesn't do anything, since we don't have any means to
|
|
539
|
-
// abort the running queryFn.
|
|
540
|
-
abortCurrentQuery: (reason) => {
|
|
541
|
-
const controller = query.getAbortControllerByKey(queryKey);
|
|
542
|
-
controller?.abort(reason);
|
|
543
|
-
return Boolean(controller);
|
|
544
|
-
},
|
|
545
|
-
getCachedOrFetch: async () => {
|
|
546
|
-
const data = await query.getCachedOrFetch(...stableArgs);
|
|
547
|
-
return nonNil(
|
|
548
|
-
data.data,
|
|
549
|
-
typeof data.error === "string" ? data.error : JSON.stringify(data.error)
|
|
550
|
-
);
|
|
551
|
-
},
|
|
552
|
-
refetch: () => {
|
|
553
|
-
return executeQuery(true);
|
|
554
|
-
},
|
|
555
|
-
setData: (data, dataUpdatedMs) => {
|
|
556
|
-
query.setData(queryKey, data, dataUpdatedMs);
|
|
557
|
-
},
|
|
558
|
-
deleteData: () => {
|
|
559
|
-
query.deleteData(queryKey);
|
|
560
|
-
}
|
|
561
|
-
};
|
|
562
|
-
}, [
|
|
563
|
-
executeQuery,
|
|
564
|
-
lastNonEmptyData,
|
|
565
|
-
query,
|
|
566
|
-
queryKey,
|
|
567
|
-
queryStateValue,
|
|
568
|
-
stableArgs
|
|
569
|
-
]);
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
export {
|
|
573
|
-
SharedQueryConfig,
|
|
574
|
-
configureSharedQuery,
|
|
575
|
-
sharedQuery,
|
|
576
|
-
useSharedQuery
|
|
577
|
-
};
|
package/chunk-HRE7YPUJ.min.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var g=Object.create;var e=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var m=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports),n=(b,a)=>{for(var c in a)e(b,c,{get:a[c],enumerable:!0})},l=(b,a,c,f)=>{if(a&&typeof a=="object"||typeof a=="function")for(let d of i(a))!k.call(b,d)&&d!==c&&e(b,d,{get:()=>a[d],enumerable:!(f=h(a,d))||f.enumerable});return b};var o=(b,a,c)=>(c=b!=null?g(j(b)):{},l(a||!b||!b.__esModule?e(c,"default",{value:b,enumerable:!0}):c,b));export{m as a,n as b,o as c};
|
|
2
|
-
//# sourceMappingURL=chunk-HRE7YPUJ.min.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/chunk-IS3BZTWE.cjs
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __create = Object.create;
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
-
var __commonJS = (cb, mod) => function __require() {
|
|
8
|
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
|
-
};
|
|
10
|
-
var __export = (target, all) => {
|
|
11
|
-
for (var name in all)
|
|
12
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
-
};
|
|
14
|
-
var __copyProps = (to, from, except, desc) => {
|
|
15
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
-
for (let key of __getOwnPropNames(from))
|
|
17
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
18
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
19
|
-
}
|
|
20
|
-
return to;
|
|
21
|
-
};
|
|
22
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
23
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
24
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
25
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
26
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
27
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
28
|
-
mod
|
|
29
|
-
));
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
exports.__commonJS = __commonJS; exports.__export = __export; exports.__toESM = __toESM;
|
package/chunk-JOHZV3FD.min.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _lodashes = require('lodash-es');var _react = require('react');function f(t){let[e,r]=_react.useState.call(void 0, t);return _react.useMemo.call(void 0, ()=>_lodashes.isEqual.call(void 0, e,t)?e:(r(t),t),[e,t])}exports.a = f;
|
|
2
|
-
//# sourceMappingURL=chunk-JOHZV3FD.min.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/useDeepMemo.ts"],"names":["useDeepMemo","value","state","setState","useState","useMemo","isEqual"],"mappings":"AAYA,8GAAwB,8BACU,SAMlBA,CAAAA,CAAeC,CAAAA,CAAa,CAC1C,GAAM,CAACC,CAAAA,CAAOC,CAAQ,CAAA,CAAIC,6BAAAA,CAAiB,CAAA,CAE3C,OAAOC,4BAAAA,CAAQ,CAAA,EACTC,+BAAAA,CAAQJ,CAAOD,CAAK,CAAA,CACfC,CAAAA,CAAAA,CAKTC,CAAAA,CAASF,CAAK,CAAA,CAEPA,CAAAA,CAAAA,CACN,CAACC,CAAAA,CAAOD,CAAK,CAAC,CACnB,CAAA,cAAA","file":"/Users/choksheaklau/src/react-utils/dist/chunk-JOHZV3FD.min.cjs","sourcesContent":["/**\n * @packageDocumentation\n *\n * Provides a memoized value in React where the value is checked for deep\n * equality. If the value has changed, but is deeply equal to the previous\n * value, then useDeepMemo will return the same reference to the previous\n * value and ignore the latest value.\n *\n * This is mainly used in shared queries to check for changes in the query\n * arguments, but it might be useful for your own use cases.\n */\n\nimport { isEqual } from \"lodash-es\";\nimport { useMemo, useState } from \"react\";\n\n/**\n * Provides a stable value for T based on deep equality. The deep equality is\n * determined by the `isEqual()` function in lodash.\n */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"]}
|
package/chunk-KGN4HQPP.min.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});function e(n){let t=new Set;return JSON.stringify(n,(s,r)=>{if(typeof r=="function")throw new Error("Functions should not be passed into query parameters");if(!r||typeof r!="object"||Array.isArray(r))return r;if(t.has(r))return"[Circular]";if(t.add(r),r!==n)try{JSON.stringify(r)}catch (e2){return"[Unserializable]"}return Object.keys(r).sort().reduce((i,o)=>(i[o]=r[o],i),{})})}exports.a = e;
|
|
2
|
-
//# sourceMappingURL=chunk-KGN4HQPP.min.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stringify.ts"],"names":["stringifyDeterministicForKeys","params","cache","_","value","result","key"],"mappings":"AAmBO,kFAASA,CAAAA,CAA8BC,CAAAA,CAAyB,CACrE,IAAMC,CAAAA,CAAQ,IAAI,GAAA,CAElB,OAAO,IAAA,CAAK,SAAA,CAAUD,CAAAA,CAAQ,CAACE,CAAAA,CAAGC,CAAAA,CAAAA,EAAU,CAC1C,EAAA,CAAI,OAAOA,CAAAA,EAAU,UAAA,CACnB,MAAM,IAAI,KAAA,CAAM,sDAAsD,CAAA,CAGxE,EAAA,CAAI,CAACA,CAAAA,EAAS,OAAOA,CAAAA,EAAU,QAAA,EAAY,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,CAC5D,OAAOA,CAAAA,CAGT,EAAA,CAAIF,CAAAA,CAAM,GAAA,CAAIE,CAAK,CAAA,CAEjB,MAAO,YAAA,CAOT,EAAA,CAJAF,CAAAA,CAAM,GAAA,CAAIE,CAAK,CAAA,CAIXA,CAAAA,GAAUH,CAAAA,CACZ,GAAI,CACF,IAAA,CAAK,SAAA,CAAUG,CAAK,CACtB,CAAA,UAAQ,CACN,MAAO,kBACT,CAGF,OAAO,MAAA,CAAO,IAAA,CAAKA,CAAK,CAAA,CACrB,IAAA,CAAK,CAAA,CACL,MAAA,CACC,CAACC,CAAAA,CAAiCC,CAAAA,CAAAA,EAAAA,CAChCD,CAAAA,CAAOC,CAAG,CAAA,CAAIF,CAAAA,CAAME,CAAG,CAAA,CAChBD,CAAAA,CAAAA,CAET,CAAC,CACH,CACJ,CAAC,CACH,CAAA,cAAA","file":"/Users/choksheaklau/src/react-utils/dist/chunk-KGN4HQPP.min.cjs","sourcesContent":["/**\n * @packageDocumentation\n *\n * Implements special stringify for use in the shared queries. This will likely\n * not be reusable for your own use cases.\n *\n * Normally you will not need to use this module directly, but if you have a\n * need for it, feel free to use it.\n */\n\n/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n"]}
|