@hyper-fetch/react 9.5.1 → 9.6.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.
Files changed (52) hide show
  1. package/__tests__/features/helpers/use-request-events/use-request-events.mapper-failure.spec.ts +215 -0
  2. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.base.spec.tsx +745 -0
  3. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.boundaries.spec.tsx +362 -0
  4. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.edge.spec.tsx +1043 -0
  5. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.matrix.spec.tsx +441 -0
  6. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.random.spec.tsx +121 -0
  7. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.refetch.spec.tsx +567 -0
  8. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.start-over.spec.tsx +353 -0
  9. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +128 -0
  10. package/__tests__/features/use-submit/use-submit.unmount.spec.ts +310 -0
  11. package/__tests__/utils/use-infinite-fetch.modes.ts +131 -0
  12. package/__tests__/utils/use-infinite-fetch.utils.ts +90 -0
  13. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
  14. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
  15. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
  16. package/dist/hooks/use-infinite-fetch/index.d.ts +4 -0
  17. package/dist/hooks/use-infinite-fetch/index.d.ts.map +1 -0
  18. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.constants.d.ts +22 -0
  19. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.constants.d.ts.map +1 -0
  20. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts +21 -0
  21. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -0
  22. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.requests.d.ts +19 -0
  23. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.requests.d.ts.map +1 -0
  24. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +119 -0
  25. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -0
  26. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.types.d.ts +48 -0
  27. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.types.d.ts.map +1 -0
  28. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +172 -0
  29. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -0
  30. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +15 -0
  31. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -0
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.mjs +934 -13
  35. package/dist/index.mjs.map +1 -1
  36. package/dist/provider/provider.types.d.ts +2 -0
  37. package/dist/provider/provider.types.d.ts.map +1 -1
  38. package/package.json +2 -3
  39. package/src/helpers/use-request-events/use-request-events.hooks.ts +13 -7
  40. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +3 -5
  41. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +4 -5
  42. package/src/hooks/use-infinite-fetch/index.ts +3 -0
  43. package/src/hooks/use-infinite-fetch/use-infinite-fetch.constants.ts +25 -0
  44. package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +389 -0
  45. package/src/hooks/use-infinite-fetch/use-infinite-fetch.requests.ts +98 -0
  46. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +780 -0
  47. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.types.ts +49 -0
  48. package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +195 -0
  49. package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +44 -0
  50. package/src/index.ts +1 -0
  51. package/src/provider/provider.types.ts +3 -0
  52. package/__tests__/features/use-fetch/use-fetch.infinite.ts +0 -39
@@ -0,0 +1,780 @@
1
+ import type {
2
+ CacheValueType,
3
+ ClientInstance,
4
+ PaginationConfig,
5
+ PaginationPageContext,
6
+ RequestInstance,
7
+ } from "@hyper-fetch/core";
8
+ import {
9
+ getCachedPages,
10
+ getHasNextPage,
11
+ getHasPreviousPage,
12
+ getInitialPageParam,
13
+ getNextPageParam,
14
+ getPageItems,
15
+ getPageRequest,
16
+ getPageTotal,
17
+ getPaginationMode,
18
+ getPreviousPageParam,
19
+ replaceEqualDeep,
20
+ scopeKey,
21
+ stringifyKey,
22
+ } from "@hyper-fetch/core";
23
+ import { isStaleCacheData } from "helpers/use-tracked-state/use-tracked-state.utils";
24
+ import { pickInitialCacheData } from "hydrate/hydrate.utils";
25
+
26
+ import { isCancelledResponse, loadPage } from "./use-infinite-fetch.requests";
27
+ import type {
28
+ FetchedPage,
29
+ InfinitePage,
30
+ InfiniteSnapshot,
31
+ InfiniteStoreOptions,
32
+ Operation,
33
+ OperationKind,
34
+ } from "./use-infinite-fetch.store.types";
35
+ import type { InfinitePageEvent } from "./use-infinite-fetch.types";
36
+
37
+ // Render and commit are separate steps, a store waits this long for the component that created it
38
+ const unusedStoreTime = 1000;
39
+
40
+ const stores = new WeakMap<ClientInstance, Map<string, InfiniteStore>>();
41
+
42
+ const getStores = (client: ClientInstance) => {
43
+ let clientStores = stores.get(client);
44
+ if (!clientStores) {
45
+ clientStores = new Map();
46
+ stores.set(client, clientStores);
47
+ }
48
+ return clientStores;
49
+ };
50
+
51
+ const isSameSnapshot = (a: InfiniteSnapshot, b: InfiniteSnapshot) => {
52
+ return (Object.keys(a) as (keyof InfiniteSnapshot)[]).every((key) => a[key] === b[key]);
53
+ };
54
+
55
+ /**
56
+ * State of a single list. Hooks showing the same list share one store, so they stay in sync and never request
57
+ * the same page twice. Pages are ordinary requests under their own cache keys - nothing extra is stored.
58
+ *
59
+ * Fetches run one at a time: every page depends on the list as it was when its value was computed.
60
+ */
61
+ export class InfiniteStore {
62
+ private listeners = new Set<VoidFunction>();
63
+ private pageListeners = new Set<(event: InfinitePageEvent<any>) => void>();
64
+ private pages: InfinitePage[] = [];
65
+ // Values of pages dropped by `maxPages`, a cursor list may have no other way of going back to them
66
+ private droppedParams: unknown[] = [];
67
+ private queue: Operation[] = [];
68
+ private running: Operation | null = null;
69
+ private cancellers = new Set<VoidFunction>();
70
+ // Pages being refetched - their cache events wait for the whole list to be swapped at once
71
+ private refetchedKeys = new Set<string>();
72
+ private unmountCacheListeners: VoidFunction | null = null;
73
+ private unusedTimer: ReturnType<typeof setTimeout> | null = null;
74
+ private started = false;
75
+ private settled = false;
76
+ private firstFetch: Promise<any> = Promise.resolve(null);
77
+ private nextPageError = false;
78
+ private previousPageError = false;
79
+ private result: { error: any; status: any; extra: any; success: boolean } = {
80
+ error: null,
81
+ status: null,
82
+ extra: null,
83
+ success: false,
84
+ };
85
+ private snapshot: InfiniteSnapshot;
86
+
87
+ constructor(
88
+ readonly key: string,
89
+ private options: InfiniteStoreOptions,
90
+ ) {
91
+ getPaginationMode(options.pagination);
92
+ this.restorePages();
93
+ this.snapshot = this.createSnapshot();
94
+ }
95
+
96
+ // ******************
97
+ // State
98
+ // ******************
99
+
100
+ getSnapshot = () => this.snapshot;
101
+
102
+ subscribe = (listener: VoidFunction) => {
103
+ this.listeners.add(listener);
104
+ if (this.listeners.size === 1) {
105
+ this.attach();
106
+ }
107
+
108
+ return () => {
109
+ this.listeners.delete(listener);
110
+ if (this.listeners.size === 0) {
111
+ this.detach();
112
+ }
113
+ };
114
+ };
115
+
116
+ onPage = (listener: (event: InfinitePageEvent<any>) => void) => {
117
+ this.pageListeners.add(listener);
118
+ return () => {
119
+ this.pageListeners.delete(listener);
120
+ };
121
+ };
122
+
123
+ /** Callbacks can capture values of the latest render */
124
+ setPagination = (pagination: PaginationConfig) => {
125
+ this.options.pagination = pagination;
126
+ };
127
+
128
+ hasPages = () => this.pages.length > 0;
129
+
130
+ // ******************
131
+ // Actions
132
+ // ******************
133
+
134
+ /**
135
+ * Loads the list when it is first needed. Safe to call many times.
136
+ */
137
+ start = ({ revalidate }: { revalidate?: boolean } = {}) => {
138
+ if (this.started) {
139
+ return this.firstFetch;
140
+ }
141
+ this.started = true;
142
+
143
+ if (this.pages.length === 0) {
144
+ this.firstFetch = this.schedule("initial");
145
+ } else if (revalidate || this.getHasStalePages()) {
146
+ this.revalidate();
147
+ } else {
148
+ this.settled = true;
149
+ }
150
+ this.publish();
151
+ return this.firstFetch;
152
+ };
153
+
154
+ fetchNextPage = () => this.fetchDirection("next");
155
+
156
+ fetchPreviousPage = () => this.fetchDirection("previous");
157
+
158
+ /**
159
+ * Refetch asked for by the user: anything already refetching is older than this call and gets replaced.
160
+ */
161
+ refetch = () => {
162
+ if (this.pages.length === 0) {
163
+ return this.revalidate();
164
+ }
165
+ this.getOperations("refetch").forEach(this.cancelOperation);
166
+ return this.schedule("refetch");
167
+ };
168
+
169
+ /**
170
+ * Automatic refetch: joins the one in progress
171
+ */
172
+ revalidate = () => {
173
+ const kind = this.pages.length > 0 ? "refetch" : "initial";
174
+ return this.getOperations(kind)[0]?.promise ?? this.schedule(kind);
175
+ };
176
+
177
+ reset = () => {
178
+ this.cancelOperations();
179
+ const startParam = stringifyKey(getInitialPageParam(this.options.request, this.options.pagination));
180
+
181
+ this.pages = this.pages.filter((page) => stringifyKey(page.param) === startParam);
182
+ this.droppedParams = [];
183
+ this.nextPageError = false;
184
+ this.previousPageError = false;
185
+ this.settled = false;
186
+ this.started = true;
187
+
188
+ return this.schedule(this.pages.length > 0 ? "refetch" : "initial");
189
+ };
190
+
191
+ abort = () => {
192
+ this.cancelOperations();
193
+ this.settled = true;
194
+ this.publish();
195
+ };
196
+
197
+ /** The list is no longer on screen - stop fetching its pages */
198
+ cancelIfUnused = () => {
199
+ if (this.listeners.size === 0) {
200
+ this.cancelOperations();
201
+ }
202
+ };
203
+
204
+ /** A store that threw its error starts over when the Error Boundary renders the component again */
205
+ evictSoon = () => {
206
+ setTimeout(this.evict, 0);
207
+ };
208
+
209
+ /** Stores created while rendering are removed when the component never mounts */
210
+ scheduleUnusedCheck = () => {
211
+ this.unusedTimer = setTimeout(() => {
212
+ this.unusedTimer = null;
213
+ if (this.running || this.queue.length > 0) {
214
+ this.scheduleUnusedCheck();
215
+ } else {
216
+ this.evict();
217
+ }
218
+ }, unusedStoreTime);
219
+ };
220
+
221
+ // ******************
222
+ // Operations
223
+ // ******************
224
+
225
+ private fetchDirection = (kind: "next" | "previous") => {
226
+ if (this.pages.length === 0) {
227
+ return this.getOperations("initial")[0]?.promise ?? Promise.resolve(null);
228
+ }
229
+ const scheduled = this.getOperations(kind)[0];
230
+ if (scheduled) {
231
+ return scheduled.promise;
232
+ }
233
+ if (kind === "next" ? this.getNextParam() === undefined : !this.getPreviousTarget()) {
234
+ return Promise.resolve(null);
235
+ }
236
+ if (kind === "next") {
237
+ this.nextPageError = false;
238
+ } else {
239
+ this.previousPageError = false;
240
+ }
241
+ return this.schedule(kind);
242
+ };
243
+
244
+ private getOperations = (kind: OperationKind) => {
245
+ const operations = this.running ? [this.running, ...this.queue] : this.queue;
246
+ return operations.filter((operation) => operation.kind === kind && !operation.cancelled);
247
+ };
248
+
249
+ private schedule = (kind: OperationKind) => {
250
+ const operation = { kind, cancelled: false } as Operation;
251
+ operation.promise = new Promise<any>((resolve) => {
252
+ operation.resolve = resolve;
253
+ });
254
+
255
+ if (kind === "initial") {
256
+ this.settled = false;
257
+ }
258
+ this.queue.push(operation);
259
+ this.pump();
260
+ this.publish();
261
+ return operation.promise;
262
+ };
263
+
264
+ private pump = async () => {
265
+ if (this.running) {
266
+ return;
267
+ }
268
+ const operation = this.queue.shift();
269
+ if (!operation) {
270
+ return;
271
+ }
272
+
273
+ this.running = operation;
274
+ const previousPages = this.pages;
275
+ let response = null;
276
+ try {
277
+ response = await this.perform(operation);
278
+ } catch (error) {
279
+ this.setFailure(error);
280
+ }
281
+ this.keepValidPages(previousPages);
282
+ this.running = null;
283
+ this.refetchedKeys.clear();
284
+
285
+ if ((operation.kind === "initial" || operation.kind === "refetch") && !operation.cancelled) {
286
+ this.settled = true;
287
+ }
288
+
289
+ operation.resolve(operation.cancelled ? null : response);
290
+ this.pump();
291
+ this.publish();
292
+ };
293
+
294
+ private cancelOperation = (operation: Operation) => {
295
+ operation.cancelled = true;
296
+ if (operation === this.running) {
297
+ this.cancellers.forEach((cancel) => cancel());
298
+ this.cancellers.clear();
299
+ this.refetchedKeys.clear();
300
+ } else {
301
+ this.queue = this.queue.filter((item) => item !== operation);
302
+ operation.resolve(null);
303
+ }
304
+ };
305
+
306
+ private cancelOperations = () => {
307
+ [...this.queue, ...(this.running ? [this.running] : [])].forEach(this.cancelOperation);
308
+ };
309
+
310
+ private perform = (operation: Operation) => {
311
+ switch (operation.kind) {
312
+ case "next": {
313
+ return this.performNext(operation);
314
+ }
315
+ case "previous": {
316
+ return this.performPrevious(operation);
317
+ }
318
+ case "refetch": {
319
+ return this.performRefetch(operation);
320
+ }
321
+ default: {
322
+ return this.performInitial(operation);
323
+ }
324
+ }
325
+ };
326
+
327
+ private performInitial = async (operation: Operation) => {
328
+ const { request, pagination } = this.options;
329
+ const fetched = await this.fetchPage(operation, getInitialPageParam(request, pagination));
330
+ if (!fetched) {
331
+ return null;
332
+ }
333
+
334
+ this.setResult(fetched.response);
335
+ if (fetched.response.success) {
336
+ this.pages = [this.createPage(fetched)];
337
+ }
338
+ return fetched.response;
339
+ };
340
+
341
+ private performNext = async (operation: Operation) => {
342
+ const param = this.getNextParam();
343
+ if (param === undefined) {
344
+ return null;
345
+ }
346
+
347
+ const fetched = await this.fetchPage(operation, param);
348
+ if (!fetched) {
349
+ return null;
350
+ }
351
+
352
+ this.setResult(fetched.response);
353
+ this.nextPageError = !fetched.response.success;
354
+ if (fetched.response.success) {
355
+ this.pages = [...this.pages, this.createPage(fetched)];
356
+ this.trimPages("start");
357
+ }
358
+ return fetched.response;
359
+ };
360
+
361
+ private performPrevious = async (operation: Operation) => {
362
+ const target = this.getPreviousTarget();
363
+ if (!target) {
364
+ return null;
365
+ }
366
+
367
+ const { param } = target;
368
+ const fetched = await this.fetchPage(operation, param);
369
+ if (!fetched) {
370
+ return null;
371
+ }
372
+
373
+ this.setResult(fetched.response);
374
+ this.previousPageError = !fetched.response.success;
375
+ if (fetched.response.success) {
376
+ if (target.isDropped) {
377
+ this.droppedParams = this.droppedParams.slice(0, -1);
378
+ }
379
+ this.pages = [this.createPage(fetched), ...this.pages];
380
+ this.trimPages("end");
381
+ }
382
+ return fetched.response;
383
+ };
384
+
385
+ private performRefetch = async (operation: Operation) => {
386
+ const current = this.pages;
387
+ current.forEach((page) => this.refetchedKeys.add(page.storageKey));
388
+
389
+ return getPaginationMode(this.options.pagination) === "cursor"
390
+ ? this.refetchInOrder(operation, current)
391
+ : this.refetchAtOnce(operation, current);
392
+ };
393
+
394
+ /**
395
+ * Page and offset values do not depend on other pages, so they can be requested together
396
+ */
397
+ private refetchAtOnce = async (operation: Operation, current: InfinitePage[]) => {
398
+ const results = await Promise.all(current.map((page) => this.fetchPage(operation, page.param, true)));
399
+ if (operation.cancelled) {
400
+ return null;
401
+ }
402
+
403
+ const failed = results.find((fetched) => fetched && !fetched.response.success);
404
+ const last = failed ?? results.findLast(Boolean);
405
+
406
+ this.pages = current.map((page, index) => {
407
+ const fetched = results[index];
408
+ return fetched?.response.success ? this.createPage(fetched) : page;
409
+ });
410
+ if (last) {
411
+ this.setResult(last.response);
412
+ }
413
+ return last?.response ?? null;
414
+ };
415
+
416
+ /**
417
+ * Every cursor comes from the page before it, and the fresh data can hold different cursors than before.
418
+ * The list is replaced only when the whole chain arrived, a failure leaves it as it was.
419
+ */
420
+ private refetchInOrder = async (operation: Operation, current: InfinitePage[]) => {
421
+ const fresh: InfinitePage[] = [];
422
+ let param = current[0].param;
423
+ let response = null;
424
+
425
+ while (fresh.length < current.length) {
426
+ // Each request needs the response of the previous one
427
+ // eslint-disable-next-line no-await-in-loop
428
+ const fetched = await this.fetchPage(operation, param, true);
429
+ if (!fetched) {
430
+ return null;
431
+ }
432
+
433
+ response = fetched.response;
434
+ this.setResult(response);
435
+ if (!response.success) {
436
+ return response;
437
+ }
438
+
439
+ const page = this.createPage(fetched);
440
+ fresh.push(page);
441
+
442
+ const context = this.getContext(page, fresh);
443
+ if (!getHasNextPage(context)) {
444
+ break;
445
+ }
446
+ param = getNextPageParam(context);
447
+ }
448
+
449
+ this.pages = fresh;
450
+ return response;
451
+ };
452
+
453
+ private trimPages = (side: "start" | "end") => {
454
+ const { maxPages } = this.options;
455
+ if (!maxPages || this.pages.length <= maxPages) {
456
+ return;
457
+ }
458
+
459
+ const overflow = this.pages.length - maxPages;
460
+ if (side === "start") {
461
+ this.droppedParams = [...this.droppedParams, ...this.pages.slice(0, overflow).map((page) => page.param)];
462
+ this.pages = this.pages.slice(overflow);
463
+ } else {
464
+ this.pages = this.pages.slice(0, maxPages);
465
+ }
466
+ };
467
+
468
+ // ******************
469
+ // Requests
470
+ // ******************
471
+
472
+ private fetchPage = async (operation: Operation, param: unknown, force = false): Promise<FetchedPage | null> => {
473
+ const request = getPageRequest(this.options.request, this.options.pagination, param);
474
+ const response = await loadPage({
475
+ request,
476
+ force,
477
+ cancellers: this.cancellers,
478
+ isCancelled: () => operation.cancelled,
479
+ });
480
+
481
+ if (operation.cancelled || !response || isCancelledResponse(response)) {
482
+ return null;
483
+ }
484
+
485
+ this.pageListeners.forEach((listener) => listener({ response, request, param }));
486
+ return { param, request, response };
487
+ };
488
+
489
+ // ******************
490
+ // Pages
491
+ // ******************
492
+
493
+ private getContext = (page: InfinitePage, pages: InfinitePage[] = this.pages): PaginationPageContext => ({
494
+ request: this.options.request,
495
+ pagination: this.options.pagination,
496
+ data: page.data,
497
+ param: page.param,
498
+ pages: pages.map((item) => item.data),
499
+ });
500
+
501
+ private getNextParam = () => {
502
+ const last = this.pages.at(-1);
503
+ if (!last || !getHasNextPage(this.getContext(last))) {
504
+ return;
505
+ }
506
+ return getNextPageParam(this.getContext(last));
507
+ };
508
+
509
+ // The first page of a cursor list has no cursor, so "no value" cannot mean "no page"
510
+ private getPreviousTarget = (): { param: unknown; isDropped: boolean } | null => {
511
+ const first = this.pages[0];
512
+ if (!first) {
513
+ return null;
514
+ }
515
+ if (this.droppedParams.length > 0) {
516
+ return { param: this.droppedParams.at(-1), isDropped: true };
517
+ }
518
+ if (getHasPreviousPage(this.getContext(first))) {
519
+ return { param: getPreviousPageParam(this.getContext(first)), isDropped: false };
520
+ }
521
+ return null;
522
+ };
523
+
524
+ private getHasStalePages = () => {
525
+ return this.pages.some((page) => {
526
+ const value = this.readValue(page.request);
527
+ return !value || isStaleCacheData(value.staleTime, value.responseTimestamp);
528
+ });
529
+ };
530
+
531
+ private readValue = (request: RequestInstance) => {
532
+ const { client } = request;
533
+ const storageKey = scopeKey(request.cacheKey, request.scope);
534
+ return pickInitialCacheData<CacheValueType>(
535
+ client.cache.get(storageKey),
536
+ this.options.hydration?.get(client, storageKey),
537
+ );
538
+ };
539
+
540
+ /** Responses go through the response mapper of the request, an asynchronous one cannot be read synchronously */
541
+ private mapValue = (request: RequestInstance, value: CacheValueType) => {
542
+ const mapped: any = request.unstable_responseMapper ? request.unstable_responseMapper(value as any) : value;
543
+ return mapped instanceof Promise ? undefined : mapped;
544
+ };
545
+
546
+ private createPage = ({ param, request, response }: FetchedPage): InfinitePage => {
547
+ // Reading the cache keeps changes made after the response arrived, like optimistic updates
548
+ const value = this.readValue(request);
549
+ const cached =
550
+ value && value.responseTimestamp >= response.responseTimestamp ? this.mapValue(request, value) : null;
551
+
552
+ return {
553
+ param,
554
+ request,
555
+ storageKey: scopeKey(request.cacheKey, request.scope),
556
+ data: cached?.success ? cached.data : response.data,
557
+ responseTimestamp: response.responseTimestamp,
558
+ };
559
+ };
560
+
561
+ private restorePages = () => {
562
+ const { request, pagination, maxPages } = this.options;
563
+
564
+ this.pages = getCachedPages({
565
+ request,
566
+ pagination,
567
+ maxPages,
568
+ read: (pageRequest) => {
569
+ const value = this.readValue(pageRequest);
570
+ const mapped = value ? this.mapValue(pageRequest, value) : null;
571
+ return mapped?.success ? { ...value, data: mapped.data } : null;
572
+ },
573
+ }).map(({ param, request: pageRequest, value }) => ({
574
+ param,
575
+ request: pageRequest,
576
+ storageKey: scopeKey(pageRequest.cacheKey, pageRequest.scope),
577
+ data: value.data,
578
+ responseTimestamp: Number(value.responseTimestamp),
579
+ }));
580
+ };
581
+
582
+ /** Picks up everything that happened between rendering and mounting */
583
+ private syncPages = () => {
584
+ if (this.running || this.queue.length > 0) {
585
+ return;
586
+ }
587
+ if (this.pages.length === 0) {
588
+ this.restorePages();
589
+ return;
590
+ }
591
+
592
+ this.pages = this.pages.map((page) => {
593
+ const value = this.readValue(page.request);
594
+ const mapped = value ? this.mapValue(page.request, value) : null;
595
+ return mapped?.success
596
+ ? { ...page, data: mapped.data, responseTimestamp: Number(value?.responseTimestamp) }
597
+ : page;
598
+ });
599
+ };
600
+
601
+ private setFailure = (error: unknown) => {
602
+ this.result = { error, status: null, extra: null, success: false };
603
+ };
604
+
605
+ /**
606
+ * Pagination callbacks read the data of every page. When one of them throws, the page that caused it is not
607
+ * used and the error is reported instead of breaking the list.
608
+ */
609
+ private keepValidPages = (previousPages: InfinitePage[]) => {
610
+ try {
611
+ this.createSnapshot();
612
+ } catch (error) {
613
+ this.pages = previousPages;
614
+ this.setFailure(error);
615
+ }
616
+ };
617
+
618
+ private setResult = (response: any) => {
619
+ this.result = {
620
+ error: response.success ? null : response.error,
621
+ status: response.status,
622
+ extra: response.extra,
623
+ success: response.success,
624
+ };
625
+ };
626
+
627
+ // ******************
628
+ // Cache
629
+ // ******************
630
+
631
+ private attach = () => {
632
+ if (this.unusedTimer) {
633
+ clearTimeout(this.unusedTimer);
634
+ this.unusedTimer = null;
635
+ }
636
+
637
+ const { client } = this.options.request;
638
+ const clientStores = getStores(client);
639
+ if (!clientStores.has(this.key) && client.mode !== "server") {
640
+ clientStores.set(this.key, this);
641
+ }
642
+
643
+ const { cache } = client;
644
+ const unmountData = cache.events.onData(this.handleCacheData);
645
+ const unmountInvalidate = cache.events.onInvalidate(this.handleCacheChange);
646
+ const unmountDelete = cache.events.onDelete(this.handleCacheChange);
647
+
648
+ this.unmountCacheListeners = () => {
649
+ unmountData();
650
+ unmountInvalidate();
651
+ unmountDelete();
652
+ };
653
+
654
+ this.syncPages();
655
+ this.publish();
656
+ };
657
+
658
+ private detach = () => {
659
+ this.unmountCacheListeners?.();
660
+ this.unmountCacheListeners = null;
661
+ this.evict();
662
+ };
663
+
664
+ private evict = () => {
665
+ if (this.listeners.size > 0) {
666
+ return;
667
+ }
668
+ const clientStores = getStores(this.options.request.client);
669
+ if (clientStores.get(this.key) === this) {
670
+ clientStores.delete(this.key);
671
+ }
672
+ };
673
+
674
+ private handleCacheData = (value: CacheValueType) => {
675
+ const storageKey = scopeKey(value.cacheKey, value.scope ?? null);
676
+ if (!value.success || this.refetchedKeys.has(storageKey)) {
677
+ return;
678
+ }
679
+
680
+ const index = this.pages.findIndex((page) => page.storageKey === storageKey);
681
+ const page = this.pages[index];
682
+ const mapped = page ? this.mapValue(page.request, value) : null;
683
+ if (!page || !mapped?.success) {
684
+ return;
685
+ }
686
+
687
+ const previousPages = this.pages;
688
+ this.pages = this.pages.map((item, itemIndex) => {
689
+ return itemIndex === index
690
+ ? { ...item, data: mapped.data, responseTimestamp: Number(value.responseTimestamp) }
691
+ : item;
692
+ });
693
+ this.keepValidPages(previousPages);
694
+ this.publish();
695
+ };
696
+
697
+ private hasInvalidation = false;
698
+
699
+ /**
700
+ * Invalidated data may have changed after a running refetch started, so that refetch is replaced.
701
+ * Invalidating by a pattern reports every key on its own, all of them are handled by one refetch.
702
+ */
703
+ private handleCacheChange = (key: string) => {
704
+ const isLoaded = this.pages.some((page) => page.storageKey === key || page.request.cacheKey === key);
705
+ if (!isLoaded || this.hasInvalidation) {
706
+ return;
707
+ }
708
+
709
+ this.hasInvalidation = true;
710
+ queueMicrotask(() => {
711
+ this.hasInvalidation = false;
712
+ if (this.listeners.size > 0) {
713
+ this.refetch();
714
+ }
715
+ });
716
+ };
717
+
718
+ // ******************
719
+ // Snapshot
720
+ // ******************
721
+
722
+ private createSnapshot = (): InfiniteSnapshot => {
723
+ const { structuralSharing = true } = this.options;
724
+ const previous = this.snapshot as InfiniteSnapshot | undefined;
725
+ const share = <T>(prev: T | undefined, next: T) =>
726
+ structuralSharing && prev ? replaceEqualDeep(prev, next) : next;
727
+
728
+ const contexts = this.pages.map((page) => this.getContext(page));
729
+ const last = contexts.at(-1);
730
+ const totals = contexts.map(getPageTotal).filter((total) => total !== null);
731
+ const operations = [...this.queue, ...(this.running ? [this.running] : [])].filter((item) => !item.cancelled);
732
+ const isRunning = (kind: OperationKind) => operations.some((item) => item.kind === kind);
733
+
734
+ return {
735
+ items: share(previous?.items, contexts.flatMap((context) => getPageItems(context))),
736
+ data: share(previous?.data, this.pages.map((page) => page.data)),
737
+ pageParams: share(previous?.pageParams, this.pages.map((page) => page.param)),
738
+ total: totals.length > 0 ? (totals.at(-1) as number) : null,
739
+ hasNextPage: !!last && this.getNextParam() !== undefined,
740
+ hasPreviousPage: !!this.getPreviousTarget(),
741
+ loading: this.pages.length === 0 && !this.settled,
742
+ isFetching: operations.length > 0,
743
+ isRefetching: isRunning("refetch"),
744
+ isFetchingNextPage: isRunning("next"),
745
+ isFetchingPreviousPage: isRunning("previous"),
746
+ isFetchNextPageError: this.nextPageError,
747
+ isFetchPreviousPageError: this.previousPageError,
748
+ ...this.result,
749
+ };
750
+ };
751
+
752
+ private publish = () => {
753
+ const snapshot = this.createSnapshot();
754
+ if (isSameSnapshot(this.snapshot, snapshot)) {
755
+ return;
756
+ }
757
+ this.snapshot = snapshot;
758
+ this.listeners.forEach((listener) => listener());
759
+ };
760
+ }
761
+
762
+ /**
763
+ * Returns the store of the list, shared between all the mounted hooks showing it.
764
+ * Server renders never share one: a client can serve many users at the same time.
765
+ */
766
+ export const getInfiniteStore = (key: string, options: InfiniteStoreOptions) => {
767
+ const { client } = options.request;
768
+ if (client.mode === "server" || typeof window === "undefined") {
769
+ return new InfiniteStore(key, options);
770
+ }
771
+
772
+ const clientStores = getStores(client);
773
+ let store = clientStores.get(key);
774
+ if (!store) {
775
+ store = new InfiniteStore(key, options);
776
+ clientStores.set(key, store);
777
+ store.scheduleUnusedCheck();
778
+ }
779
+ return store;
780
+ };