@hyper-fetch/react 9.5.2 → 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 (47) hide show
  1. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.base.spec.tsx +745 -0
  2. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.boundaries.spec.tsx +362 -0
  3. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.edge.spec.tsx +1043 -0
  4. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.matrix.spec.tsx +441 -0
  5. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.random.spec.tsx +121 -0
  6. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.refetch.spec.tsx +567 -0
  7. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.start-over.spec.tsx +353 -0
  8. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +128 -0
  9. package/__tests__/features/use-submit/use-submit.unmount.spec.ts +310 -0
  10. package/__tests__/utils/use-infinite-fetch.modes.ts +131 -0
  11. package/__tests__/utils/use-infinite-fetch.utils.ts +90 -0
  12. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
  13. package/dist/hooks/use-infinite-fetch/index.d.ts +4 -0
  14. package/dist/hooks/use-infinite-fetch/index.d.ts.map +1 -0
  15. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.constants.d.ts +22 -0
  16. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.constants.d.ts.map +1 -0
  17. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts +21 -0
  18. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -0
  19. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.requests.d.ts +19 -0
  20. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.requests.d.ts.map +1 -0
  21. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +119 -0
  22. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -0
  23. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.types.d.ts +48 -0
  24. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.types.d.ts.map +1 -0
  25. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +172 -0
  26. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -0
  27. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +15 -0
  28. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -0
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.mjs +914 -2
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/provider/provider.types.d.ts +2 -0
  34. package/dist/provider/provider.types.d.ts.map +1 -1
  35. package/package.json +1 -1
  36. package/src/helpers/use-request-events/use-request-events.hooks.ts +11 -1
  37. package/src/hooks/use-infinite-fetch/index.ts +3 -0
  38. package/src/hooks/use-infinite-fetch/use-infinite-fetch.constants.ts +25 -0
  39. package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +389 -0
  40. package/src/hooks/use-infinite-fetch/use-infinite-fetch.requests.ts +98 -0
  41. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +780 -0
  42. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.types.ts +49 -0
  43. package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +195 -0
  44. package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +44 -0
  45. package/src/index.ts +1 -0
  46. package/src/provider/provider.types.ts +3 -0
  47. package/__tests__/features/use-fetch/use-fetch.infinite.ts +0 -39
@@ -2,6 +2,7 @@ import { RequestInstance } from '@hyper-fetch/core';
2
2
  import { UseCacheOptionsType } from '../hooks/use-cache';
3
3
  import { UseEmitterOptionsType } from '../hooks/use-emitter';
4
4
  import { UseFetchOptionsType } from '../hooks/use-fetch';
5
+ import { UseInfiniteFetchConfigType } from '../hooks/use-infinite-fetch';
5
6
  import { UseListenerOptionsType } from '../hooks/use-listener';
6
7
  import { UseQueueOptionsType } from '../hooks/use-queue';
7
8
  import { UseSubmitOptionsType } from '../hooks/use-submit';
@@ -9,6 +10,7 @@ import { default as React } from 'react';
9
10
  type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
10
11
  export type ProviderOptionsType = {
11
12
  useFetchConfig?: Partial<DistributiveOmit<UseFetchOptionsType<RequestInstance>, "select">>;
13
+ useInfiniteFetchConfig?: UseInfiniteFetchConfigType;
12
14
  useSubmitConfig?: Partial<DistributiveOmit<UseSubmitOptionsType<RequestInstance>, "select">>;
13
15
  useCacheConfig?: Partial<Omit<UseCacheOptionsType<RequestInstance>, "select">>;
14
16
  useQueueConfig?: Partial<UseQueueOptionsType>;
@@ -1 +1 @@
1
- {"version":3,"file":"provider.types.d.ts","sourceRoot":"","sources":["../../src/provider/provider.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B,KAAK,gBAAgB,CAAC,CAAC,EAAE,CAAC,SAAS,WAAW,IAAI,CAAC,SAAS,OAAO,GAAG,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,GA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AC5B,SAAS,EAAE,CAAC,SAAS,EAAE,mBAAmB,KAAK,IAAI,CAAC;CACrD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyper-fetch/react",
3
- "version": "9.5.2",
3
+ "version": "9.6.0",
4
4
  "description": "React hooks and utils for the hyper-fetch",
5
5
  "author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
6
6
  "homepage": "https://hyperfetch.bettertyped.com/",
@@ -1,4 +1,4 @@
1
- import { useWillUnmount } from "@better-hooks/lifecycle";
1
+ import { useIsMounted, useWillUnmount } from "@better-hooks/lifecycle";
2
2
  import type {
3
3
  ExtractErrorType,
4
4
  ExtractResponseType,
@@ -62,6 +62,8 @@ export const useRequestEvents = <R extends RequestInstance>({
62
62
 
63
63
  const lifecycleEvents = useRef<UseRequestEventsLifecycleMap>(new Map());
64
64
  const dataEvents = useRef<UseRequestEventsDataMap | null>(null);
65
+ // Sending can outlive the component - the unmount cleanup never sees listeners attached after it ran
66
+ const isMounted = useIsMounted();
65
67
 
66
68
  const removeLifecycleListener = (requestId: string) => {
67
69
  const event = lifecycleEvents.current.get(requestId);
@@ -192,6 +194,10 @@ export const useRequestEvents = <R extends RequestInstance>({
192
194
  };
193
195
 
194
196
  const addCacheDataListener = (req: R) => {
197
+ if (!isMounted.current) {
198
+ return () => undefined;
199
+ }
200
+
195
201
  // Data handlers
196
202
  // Core emits these events by the logical keys; the handlers skip events of other scopes
197
203
  const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));
@@ -222,6 +228,10 @@ export const useRequestEvents = <R extends RequestInstance>({
222
228
  // ******************
223
229
 
224
230
  const addLifecycleListeners = (req: R, requestId?: string, optimisticResult?: OptimisticCallbackResult<any>) => {
231
+ if (!isMounted.current) {
232
+ return () => undefined;
233
+ }
234
+
225
235
  /**
226
236
  * useFetch handles requesting by general keys
227
237
  * This makes it possible to deduplicate requests from different places and share data
@@ -0,0 +1,3 @@
1
+ export * from "./use-infinite-fetch.constants";
2
+ export * from "./use-infinite-fetch.hooks";
3
+ export * from "./use-infinite-fetch.types";
@@ -0,0 +1,25 @@
1
+ import { Time } from "@hyper-fetch/core";
2
+
3
+ import type { UseInfiniteFetchConfigType } from "./use-infinite-fetch.types";
4
+
5
+ export const useInfiniteFetchDefaultOptions = {
6
+ suspense: false,
7
+ throwOnError: false,
8
+ dependencies: [],
9
+ disabled: false,
10
+ dependencyTracking: true,
11
+ // Pages restored from the cache are refetched only once they are stale
12
+ revalidate: false,
13
+ keepPreviousData: "auto",
14
+ refresh: false,
15
+ refreshTime: Time.HOUR,
16
+ refetchBlurred: true,
17
+ refetchOnBlur: false,
18
+ refetchOnFocus: false,
19
+ refetchOnReconnect: false,
20
+ structuralSharing: true,
21
+ bounce: false,
22
+ bounceType: "debounce",
23
+ bounceTime: 400,
24
+ bounceTimeout: 400,
25
+ } satisfies Required<UseInfiniteFetchConfigType>;
@@ -0,0 +1,389 @@
1
+ import { useDidUpdate } from "@better-hooks/lifecycle";
2
+ import { useDebounce, useThrottle } from "@better-hooks/performance";
3
+ import type {
4
+ ExtractErrorType,
5
+ Pagination,
6
+ PaginationConfig,
7
+ PaginationItem,
8
+ RequestInstance,
9
+ } from "@hyper-fetch/core";
10
+ import { replaceEqualDeep } from "@hyper-fetch/core";
11
+ import { useHydration } from "hydrate/hydrate";
12
+ import { useProvider } from "provider";
13
+ import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
14
+ import { createTrackedProxy, getBounceData } from "utils";
15
+
16
+ import { useInfiniteFetchDefaultOptions } from "./use-infinite-fetch.constants";
17
+ import type { InfiniteStore } from "./use-infinite-fetch.store";
18
+ import { getInfiniteStore } from "./use-infinite-fetch.store";
19
+ import type { InfiniteSnapshot } from "./use-infinite-fetch.store.types";
20
+ import type { UseInfiniteFetchOptionsType, UseInfiniteFetchReturnType } from "./use-infinite-fetch.types";
21
+ import { getInfiniteKey, getShouldKeepPreviousList, getUniqueItems } from "./use-infinite-fetch.utils";
22
+
23
+ // What decides about a returned value - the list on screen also depends on the new list still loading
24
+ const trackedSources: Record<string, (keyof InfiniteSnapshot)[]> = {
25
+ items: ["items", "loading"],
26
+ pages: ["data", "loading"],
27
+ pageParams: ["pageParams", "loading"],
28
+ total: ["total", "loading"],
29
+ isPreviousData: ["data", "loading"],
30
+ loading: ["data", "loading"],
31
+ };
32
+
33
+ const trackedKeys = [
34
+ "items",
35
+ "pages",
36
+ "pageParams",
37
+ "total",
38
+ "hasNextPage",
39
+ "hasPreviousPage",
40
+ "loading",
41
+ "isFetching",
42
+ "isRefetching",
43
+ "isFetchingNextPage",
44
+ "isFetchingPreviousPage",
45
+ "isFetchNextPageError",
46
+ "isFetchPreviousPageError",
47
+ "isPreviousData",
48
+ "error",
49
+ "status",
50
+ "extra",
51
+ "success",
52
+ ] as const;
53
+
54
+ /**
55
+ * Loads a list page by page. Say which fields page through the request, and the hook takes care of the rest:
56
+ * every page is a normal request under its own cache key, and the hook glues them together.
57
+ *
58
+ * A changed filter, sort or URL param starts a new list on its own. When to load more is up to you - call
59
+ * `fetchNextPage` from a button, an intersection observer, `onEndReached` or a virtualizer.
60
+ *
61
+ * @param request Request instance
62
+ * @param options Hook options, `pagination` is required
63
+ * @returns
64
+ * @example
65
+ * ```tsx
66
+ * const { items, hasNextPage, fetchNextPage } = useInfiniteFetch(getFeed.setQueryParams({ topic }), {
67
+ * pagination: { cursor: "cursor", next: "nextCursor", items: "data" },
68
+ * });
69
+ * ```
70
+ */
71
+ export const useInfiniteFetch = <
72
+ R extends RequestInstance,
73
+ const P extends Pagination<R>,
74
+ TSelected = PaginationItem<R, P>[],
75
+ >(
76
+ request: R,
77
+ options: UseInfiniteFetchOptionsType<R, P, TSelected>,
78
+ ): UseInfiniteFetchReturnType<R, P, TSelected> => {
79
+ const { config: globalConfig } = useProvider();
80
+ const {
81
+ pagination,
82
+ uniqueBy,
83
+ maxPages,
84
+ select,
85
+ suspense,
86
+ throwOnError,
87
+ dependencies,
88
+ disabled,
89
+ dependencyTracking,
90
+ revalidate,
91
+ keepPreviousData,
92
+ refresh,
93
+ refreshTime,
94
+ refetchBlurred,
95
+ refetchOnBlur,
96
+ refetchOnFocus,
97
+ refetchOnReconnect,
98
+ structuralSharing,
99
+ bounce,
100
+ bounceType,
101
+ bounceTime,
102
+ bounceTimeout,
103
+ } = {
104
+ ...useInfiniteFetchDefaultOptions,
105
+ ...globalConfig.useInfiniteFetchConfig,
106
+ ...options,
107
+ };
108
+
109
+ const { client } = request;
110
+ const hydration = useHydration();
111
+
112
+ const requestDebounce = useDebounce({ delay: bounceTime });
113
+ const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });
114
+ const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
115
+ const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
116
+
117
+ // ******************
118
+ // Store
119
+ // ******************
120
+
121
+ const key = getInfiniteKey(request, pagination, maxPages);
122
+ const storeRef = useRef<InfiniteStore | null>(null);
123
+ const storeClientRef = useRef(client);
124
+
125
+ if (!storeRef.current || storeRef.current.key !== key || storeClientRef.current !== client) {
126
+ storeClientRef.current = client;
127
+ storeRef.current = getInfiniteStore(key, {
128
+ request,
129
+ pagination: pagination as PaginationConfig,
130
+ maxPages,
131
+ structuralSharing,
132
+ hydration,
133
+ });
134
+ }
135
+ const store = storeRef.current;
136
+
137
+ // Rerenders only when something the component reads has changed
138
+ const usedKeys = useRef(new Set<string>()).current;
139
+ const renderedRef = useRef<{ store: InfiniteStore; snapshot: InfiniteSnapshot } | null>(null);
140
+
141
+ const getSnapshot = () => {
142
+ const next = store.getSnapshot();
143
+ const rendered = renderedRef.current;
144
+
145
+ if (dependencyTracking && rendered?.store === store) {
146
+ const hasChanged = [...usedKeys].some((usedKey) => {
147
+ const sources = trackedSources[usedKey] ?? [usedKey as keyof InfiniteSnapshot];
148
+ return sources.some((source) => rendered.snapshot[source] !== next[source]);
149
+ });
150
+ if (!hasChanged) {
151
+ return rendered.snapshot;
152
+ }
153
+ }
154
+
155
+ renderedRef.current = { store, snapshot: next };
156
+ return next;
157
+ };
158
+
159
+ const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
160
+
161
+ // ******************
162
+ // Latest values
163
+ // ******************
164
+
165
+ const callbacks = useRef<{
166
+ onSuccess?: (event: any) => void;
167
+ onError?: (event: any) => void;
168
+ onFinished?: (event: any) => void;
169
+ onReset?: VoidFunction;
170
+ }>({});
171
+
172
+ const latest = useRef({ disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect });
173
+ latest.current = { disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect };
174
+
175
+ // ******************
176
+ // Lifecycle
177
+ // ******************
178
+
179
+ useEffect(() => {
180
+ store.setPagination(pagination as PaginationConfig);
181
+ });
182
+
183
+ useEffect(() => {
184
+ return store.onPage((event) => {
185
+ if (event.response.success) {
186
+ callbacks.current.onSuccess?.(event);
187
+ } else {
188
+ callbacks.current.onError?.(event);
189
+ }
190
+ callbacks.current.onFinished?.(event);
191
+ });
192
+ }, [store]);
193
+
194
+ /**
195
+ * A new list stops the pages of the previous one, so a late response never gets in the way
196
+ */
197
+ const mountedStore = useRef<InfiniteStore | null>(null);
198
+
199
+ useEffect(() => {
200
+ const previous = mountedStore.current;
201
+ mountedStore.current = store;
202
+
203
+ if (previous && previous !== store) {
204
+ previous.cancelIfUnused();
205
+ callbacks.current.onReset?.();
206
+ }
207
+ if (disabled) {
208
+ return;
209
+ }
210
+
211
+ if (bounce && previous && previous !== store && !store.hasPages()) {
212
+ bounceFunction(() => store.start({ revalidate: latest.current.revalidate }));
213
+ } else {
214
+ store.start({ revalidate });
215
+ }
216
+ // eslint-disable-next-line react-hooks/exhaustive-deps
217
+ }, [store, disabled]);
218
+
219
+ useDidUpdate(() => {
220
+ if (!disabled) {
221
+ store.refetch();
222
+ }
223
+ }, dependencies);
224
+
225
+ useEffect(() => {
226
+ const { appManager } = client;
227
+ const handle = (option: "refetchOnBlur" | "refetchOnFocus" | "refetchOnReconnect") => () => {
228
+ if (latest.current[option] && !latest.current.disabled) {
229
+ store.revalidate();
230
+ }
231
+ };
232
+
233
+ const unmountFocus = appManager.events.onFocus(handle("refetchOnFocus"));
234
+ const unmountBlur = appManager.events.onBlur(handle("refetchOnBlur"));
235
+ const unmountOnline = appManager.events.onOnline(handle("refetchOnReconnect"));
236
+
237
+ return () => {
238
+ unmountFocus();
239
+ unmountBlur();
240
+ unmountOnline();
241
+ };
242
+ }, [client, store]);
243
+
244
+ useEffect(() => {
245
+ if (!refresh || disabled) {
246
+ return;
247
+ }
248
+
249
+ const timer = setInterval(() => {
250
+ if (client.appManager.isFocused || refetchBlurred) {
251
+ store.revalidate();
252
+ }
253
+ }, refreshTime);
254
+
255
+ return () => clearInterval(timer);
256
+ }, [client, store, refresh, refreshTime, refetchBlurred, disabled]);
257
+
258
+ // ******************
259
+ // Previous list
260
+ // ******************
261
+
262
+ const previousList = useRef<{ store: InfiniteStore; request: RequestInstance; snapshot: InfiniteSnapshot } | null>(
263
+ null,
264
+ );
265
+
266
+ useEffect(() => {
267
+ if (snapshot.data.length > 0) {
268
+ previousList.current = { store, request, snapshot };
269
+ }
270
+ });
271
+
272
+ const previous = previousList.current;
273
+ const isPreviousData =
274
+ !disabled &&
275
+ snapshot.loading &&
276
+ snapshot.data.length === 0 &&
277
+ !!previous &&
278
+ previous.store !== store &&
279
+ getShouldKeepPreviousList(keepPreviousData, previous.request, request);
280
+
281
+ const list = isPreviousData ? previous.snapshot : snapshot;
282
+
283
+ // ******************
284
+ // Suspense
285
+ // ******************
286
+
287
+ const isServer = client.mode === "server" || typeof window === "undefined";
288
+
289
+ if (suspense && !disabled && !isServer && snapshot.loading && !isPreviousData) {
290
+ throw store.start({ revalidate });
291
+ }
292
+
293
+ // ******************
294
+ // Error boundary
295
+ // ******************
296
+
297
+ if (throwOnError) {
298
+ usedKeys.add("error");
299
+ usedKeys.add("isFetching");
300
+
301
+ const error = snapshot.error as ExtractErrorType<R> | null;
302
+ const shouldThrow = typeof throwOnError === "function" ? !!error && throwOnError(error) : !!error;
303
+
304
+ if (shouldThrow && !snapshot.isFetching) {
305
+ store.evictSoon();
306
+ throw error;
307
+ }
308
+ }
309
+
310
+ // ******************
311
+ // Items
312
+ // ******************
313
+
314
+ const uniqueByRef = useRef(uniqueBy);
315
+ uniqueByRef.current = uniqueBy;
316
+ const uniqueByKey = typeof uniqueBy === "function" ? uniqueBy.toString() : uniqueBy;
317
+
318
+ const uniqueItems = useMemo(() => {
319
+ return getUniqueItems(list.items, uniqueByRef.current);
320
+ // Inline functions change on every render, the key changes only with their code
321
+ // eslint-disable-next-line react-hooks/exhaustive-deps
322
+ }, [list.items, uniqueByKey]);
323
+
324
+ const selectedRef = useRef<unknown>(null);
325
+ let items: unknown = uniqueItems;
326
+
327
+ if (select) {
328
+ const selected = select({ items: uniqueItems as PaginationItem<R, P>[], pages: list.data as any[] });
329
+ items = structuralSharing ? replaceEqualDeep(selectedRef.current, selected) : selected;
330
+ selectedRef.current = items;
331
+ }
332
+
333
+ // ******************
334
+ // Actions
335
+ // ******************
336
+
337
+ const actions = useMemo(
338
+ () => ({
339
+ fetchNextPage: () => store.fetchNextPage(),
340
+ fetchPreviousPage: () => store.fetchPreviousPage(),
341
+ refetch: () => store.refetch(),
342
+ reset: () => {
343
+ callbacks.current.onReset?.();
344
+ return store.reset();
345
+ },
346
+ abort: () => store.abort(),
347
+ onSuccess: (callback: (event: any) => void) => {
348
+ callbacks.current.onSuccess = callback;
349
+ },
350
+ onError: (callback: (event: any) => void) => {
351
+ callbacks.current.onError = callback;
352
+ },
353
+ onFinished: (callback: (event: any) => void) => {
354
+ callbacks.current.onFinished = callback;
355
+ },
356
+ onReset: (callback: VoidFunction) => {
357
+ callbacks.current.onReset = callback;
358
+ },
359
+ }),
360
+ [store],
361
+ );
362
+
363
+ return createTrackedProxy(
364
+ {
365
+ items,
366
+ pages: list.data,
367
+ pageParams: list.pageParams,
368
+ total: list.total,
369
+ hasNextPage: snapshot.hasNextPage,
370
+ hasPreviousPage: snapshot.hasPreviousPage,
371
+ loading: !disabled && snapshot.loading && !isPreviousData,
372
+ isFetching: snapshot.isFetching,
373
+ isRefetching: snapshot.isRefetching,
374
+ isFetchingNextPage: snapshot.isFetchingNextPage,
375
+ isFetchingPreviousPage: snapshot.isFetchingPreviousPage,
376
+ isFetchNextPageError: snapshot.isFetchNextPageError,
377
+ isFetchPreviousPageError: snapshot.isFetchPreviousPageError,
378
+ isPreviousData,
379
+ error: snapshot.error,
380
+ status: snapshot.status,
381
+ extra: snapshot.extra,
382
+ success: snapshot.success,
383
+ bounce: getBounceData(bounceData),
384
+ ...actions,
385
+ },
386
+ trackedKeys,
387
+ (usedKey) => usedKeys.add(usedKey),
388
+ ) as unknown as UseInfiniteFetchReturnType<R, P, TSelected>;
389
+ };
@@ -0,0 +1,98 @@
1
+ import type { RequestInstance } from "@hyper-fetch/core";
2
+ import { getErrorMessage, mapResponseForSend, scopeKey } from "@hyper-fetch/core";
3
+
4
+ type LoadPageOptions = {
5
+ request: RequestInstance;
6
+ /** Skips requests started before this fetch was asked for */
7
+ force: boolean;
8
+ /** Filled with the functions stopping this fetch */
9
+ cancellers: Set<VoidFunction>;
10
+ isCancelled: () => boolean;
11
+ };
12
+
13
+ /**
14
+ * Cancelled pages are not failures: the list simply did not need them anymore
15
+ */
16
+ export const isCancelledResponse = (response: any) => {
17
+ const message = response?.error?.message;
18
+ return (
19
+ !response?.success &&
20
+ (message === getErrorMessage("abort").message || message === getErrorMessage("deleted").message)
21
+ );
22
+ };
23
+
24
+ /**
25
+ * Joins a request started elsewhere. Cancelling only stops waiting, the request belongs to someone else.
26
+ */
27
+ const waitForResponse = (request: RequestInstance, requestId: string, cancellers: Set<VoidFunction>) => {
28
+ const { requestManager } = request.client;
29
+
30
+ return new Promise<any>((resolve) => {
31
+ const finish = (response: any) => {
32
+ unmountResponse();
33
+ unmountRemove();
34
+ cancellers.delete(cancel);
35
+ resolve(response);
36
+ };
37
+ const cancel = () => finish(null);
38
+ const unmountResponse = requestManager.events.onResponseById(requestId, ({ response, details }) => {
39
+ if (response.success || (!details.willRetry && !details.isOffline)) {
40
+ finish(response);
41
+ }
42
+ });
43
+ const unmountRemove = requestManager.events.onRemoveById(requestId, cancel);
44
+
45
+ cancellers.add(cancel);
46
+ });
47
+ };
48
+
49
+ const sendPage = async ({ request, force, cancellers }: LoadPageOptions) => {
50
+ const { fetchDispatcher } = request.client;
51
+ const pageRequest = force ? request.setDeduplicate(false) : request;
52
+ let sentRequestId = "";
53
+
54
+ const cancel = () => {
55
+ fetchDispatcher.delete(
56
+ scopeKey(request.queryKey, request.scope),
57
+ sentRequestId,
58
+ scopeKey(request.abortKey, request.scope),
59
+ );
60
+ };
61
+ cancellers.add(cancel);
62
+
63
+ const response = await (pageRequest as RequestInstance).send({
64
+ dispatcherType: "fetch",
65
+ onBeforeSent: ({ requestId }: { requestId: string }) => {
66
+ sentRequestId = requestId;
67
+ },
68
+ } as any);
69
+
70
+ cancellers.delete(cancel);
71
+ return response;
72
+ };
73
+
74
+ /**
75
+ * Loads a page, reusing the request already running for it
76
+ */
77
+ export const loadPage = async (options: LoadPageOptions) => {
78
+ const { request, force, cancellers, isCancelled } = options;
79
+
80
+ // A forced fetch must not reuse a request started before it was asked for
81
+ if (!force) {
82
+ const running = request.client.fetchDispatcher
83
+ .getRunningRequests(scopeKey(request.queryKey, request.scope))
84
+ .find((item) => item.request.cacheKey === request.cacheKey);
85
+
86
+ if (running) {
87
+ const response = await waitForResponse(request, running.requestId, cancellers);
88
+ if (response) {
89
+ return mapResponseForSend(request, response);
90
+ }
91
+ if (isCancelled()) {
92
+ return null;
93
+ }
94
+ }
95
+ }
96
+
97
+ return sendPage(options);
98
+ };