@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
@@ -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,EAA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qBAAqB,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B;;OAEG;IACH,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B;;OAEG;IACH,MAAM,CAAC,EAAE,mBAAmB,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,MAAM,EAAE,mBAAmB,CAAC;IAC5B,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.1",
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/",
@@ -28,8 +28,7 @@
28
28
  "lint": "oxlint .",
29
29
  "format": "oxfmt --write .",
30
30
  "typecheck": "tsgo --noEmit --emitDeclarationOnly false && tsgo --noEmit -p __tests__/tsconfig.json",
31
- "tests": "pnpm lint-staged",
32
- "release": "pnpm semantic-release --extends ../../release.config.js -t 'react-hyper-fetch-v${version}'"
31
+ "tests": "pnpm lint-staged"
33
32
  },
34
33
  "peerDependencies": {
35
34
  "@hyper-fetch/core": "*",
@@ -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,
@@ -11,7 +11,7 @@ import type {
11
11
  ResponseType,
12
12
  OptimisticCallbackResult,
13
13
  } from "@hyper-fetch/core";
14
- import { scopeKey } from "@hyper-fetch/core";
14
+ import { runResponseMapper, scopeKey } from "@hyper-fetch/core";
15
15
  import type {
16
16
  OnErrorCallbackType,
17
17
  OnStartCallbackType,
@@ -40,8 +40,6 @@ export const useRequestEvents = <R extends RequestInstance>({
40
40
  setCacheData,
41
41
  getIsDataProcessing,
42
42
  }: UseRequestEventsPropsType<R>): UseRequestEventsReturnType<R> => {
43
- // eslint-disable-next-line @typescript-eslint/naming-convention
44
- const { unstable_responseMapper } = request;
45
43
  const { cache, requestManager } = request.client;
46
44
 
47
45
  // ******************
@@ -64,6 +62,8 @@ export const useRequestEvents = <R extends RequestInstance>({
64
62
 
65
63
  const lifecycleEvents = useRef<UseRequestEventsLifecycleMap>(new Map());
66
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();
67
67
 
68
68
  const removeLifecycleListener = (requestId: string) => {
69
69
  const event = lifecycleEvents.current.get(requestId);
@@ -165,9 +165,7 @@ export const useRequestEvents = <R extends RequestInstance>({
165
165
 
166
166
  const handleResponse = () => {
167
167
  return (values: RequestResponseEventType<R>) => {
168
- const data = unstable_responseMapper
169
- ? unstable_responseMapper(values.response as ResponseType<any, any, ExtractAdapterType<R>>)
170
- : values.response;
168
+ const data = runResponseMapper(request, values.response);
171
169
 
172
170
  if (data instanceof Promise) {
173
171
  return (async () => {
@@ -196,6 +194,10 @@ export const useRequestEvents = <R extends RequestInstance>({
196
194
  };
197
195
 
198
196
  const addCacheDataListener = (req: R) => {
197
+ if (!isMounted.current) {
198
+ return () => undefined;
199
+ }
200
+
199
201
  // Data handlers
200
202
  // Core emits these events by the logical keys; the handlers skip events of other scopes
201
203
  const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));
@@ -226,6 +228,10 @@ export const useRequestEvents = <R extends RequestInstance>({
226
228
  // ******************
227
229
 
228
230
  const addLifecycleListeners = (req: R, requestId?: string, optimisticResult?: OptimisticCallbackResult<any>) => {
231
+ if (!isMounted.current) {
232
+ return () => undefined;
233
+ }
234
+
229
235
  /**
230
236
  * useFetch handles requesting by general keys
231
237
  * This makes it possible to deduplicate requests from different places and share data
@@ -9,7 +9,7 @@ import type {
9
9
  ExtractAdapterExtraType,
10
10
  ResponseType,
11
11
  } from "@hyper-fetch/core";
12
- import { replaceEqualDeep, scopeKey } from "@hyper-fetch/core";
12
+ import { replaceEqualDeep, runResponseMapper, scopeKey } from "@hyper-fetch/core";
13
13
  import { useHydration } from "hydrate/hydrate";
14
14
  import { useCallback, useRef, useSyncExternalStore } from "react";
15
15
  import { isEqual } from "utils";
@@ -49,7 +49,7 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
49
49
  select,
50
50
  structuralSharing = true,
51
51
  }: UseTrackedStateProps<T, TData>): UseTrackedStateReturn<T, TData> => {
52
- const { client, cacheKey, queryKey, staleTime, unstable_responseMapper } = request;
52
+ const { client, cacheKey, queryKey, staleTime } = request;
53
53
  const { cache } = client;
54
54
  const hydration = useHydration();
55
55
 
@@ -302,9 +302,7 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
302
302
  cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,
303
303
  ): Promise<void> | void => {
304
304
  setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: true });
305
- const data = unstable_responseMapper
306
- ? unstable_responseMapper(cacheData as ResponseType<any, any, ExtractAdapterType<T>>)
307
- : cacheData;
305
+ const data = runResponseMapper(request, cacheData as ResponseType<any, any, ExtractAdapterType<T>>) || cacheData;
308
306
 
309
307
  if (data instanceof Promise) {
310
308
  return (async () => {
@@ -13,7 +13,7 @@ import type {
13
13
  ExtractAdapterStatusType,
14
14
  ResponseType,
15
15
  } from "@hyper-fetch/core";
16
- import { scopeKey } from "@hyper-fetch/core";
16
+ import { runResponseMapper, scopeKey } from "@hyper-fetch/core";
17
17
  import type { UseTrackedStateType } from "helpers";
18
18
  import { initialState } from "helpers";
19
19
  import type { HydratedEntry } from "hydrate/hydrate.types";
@@ -147,7 +147,7 @@ export const getInitialState = <T extends RequestInstance>({
147
147
  /** Data from the closest `Hydrate` that was not written to the cache yet */
148
148
  hydratedEntry?: NullableType<HydratedEntry>;
149
149
  }): UseTrackedStateType<T> => {
150
- const { client, cacheKey, unstable_responseMapper } = request;
150
+ const { client, cacheKey } = request;
151
151
  const { cache } = client;
152
152
 
153
153
  const cacheData = pickInitialCacheData(
@@ -165,9 +165,8 @@ export const getInitialState = <T extends RequestInstance>({
165
165
  });
166
166
 
167
167
  if (cacheState) {
168
- const mappedData = unstable_responseMapper
169
- ? unstable_responseMapper(cacheState as ResponseType<any, any, ExtractAdapterType<T>>)
170
- : cacheState;
168
+ const mappedData =
169
+ runResponseMapper(request, cacheState as ResponseType<any, any, ExtractAdapterType<T>>) || cacheState;
171
170
  if (mappedData instanceof Promise) {
172
171
  // For the async mapper we cannot return async values
173
172
  // So we have return the initial state instead
@@ -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
+ };