@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,49 @@
1
+ import type { PaginationConfig, RequestInstance } from "@hyper-fetch/core";
2
+ import type { HydrationContextType } from "hydrate/hydrate.types";
3
+
4
+ export type OperationKind = "initial" | "next" | "previous" | "refetch";
5
+
6
+ export type Operation = {
7
+ kind: OperationKind;
8
+ cancelled: boolean;
9
+ promise: Promise<any>;
10
+ resolve: (value: any) => void;
11
+ };
12
+
13
+ export type InfinitePage = {
14
+ param: unknown;
15
+ request: RequestInstance;
16
+ storageKey: string;
17
+ data: any;
18
+ responseTimestamp: number;
19
+ };
20
+
21
+ export type FetchedPage = { param: unknown; request: RequestInstance; response: any };
22
+
23
+ export type InfiniteStoreOptions = {
24
+ request: RequestInstance;
25
+ pagination: PaginationConfig;
26
+ maxPages?: number;
27
+ structuralSharing?: boolean;
28
+ hydration?: HydrationContextType | null;
29
+ };
30
+
31
+ export type InfiniteSnapshot = {
32
+ items: unknown[];
33
+ data: unknown[];
34
+ pageParams: unknown[];
35
+ total: number | null;
36
+ hasNextPage: boolean;
37
+ hasPreviousPage: boolean;
38
+ loading: boolean;
39
+ isFetching: boolean;
40
+ isRefetching: boolean;
41
+ isFetchingNextPage: boolean;
42
+ isFetchingPreviousPage: boolean;
43
+ isFetchNextPageError: boolean;
44
+ isFetchPreviousPageError: boolean;
45
+ error: any;
46
+ status: any;
47
+ extra: any;
48
+ success: boolean;
49
+ };
@@ -0,0 +1,195 @@
1
+ import type {
2
+ ExtractAdapterExtraType,
3
+ ExtractAdapterStatusType,
4
+ ExtractAdapterType,
5
+ ExtractErrorType,
6
+ ExtractResponseType,
7
+ Pagination,
8
+ PaginationItem,
9
+ RequestInstance,
10
+ ResponseType,
11
+ } from "@hyper-fetch/core";
12
+
13
+ export type InfinitePageResponse<R extends RequestInstance> = ResponseType<
14
+ ExtractResponseType<R>,
15
+ ExtractErrorType<R>,
16
+ ExtractAdapterType<R>
17
+ >;
18
+
19
+ export type InfinitePageEvent<R extends RequestInstance> = {
20
+ /** Response of the page */
21
+ response: InfinitePageResponse<R>;
22
+ /** Request of the page */
23
+ request: R;
24
+ /** Value of the paging field used for this page */
25
+ param: unknown;
26
+ };
27
+
28
+ export type UseInfiniteFetchOptionsType<
29
+ R extends RequestInstance,
30
+ P extends Pagination<R> = Pagination<R>,
31
+ TSelected = PaginationItem<R, P>[],
32
+ > = {
33
+ /**
34
+ * Which fields of the request page through the list. Every key is checked against the request types.
35
+ */
36
+ pagination: P;
37
+ /**
38
+ * Drops items repeated across pages, for lists that shift while scrolling.
39
+ * Name a field of the item or return the identity from a function.
40
+ */
41
+ uniqueBy?: Extract<keyof PaginationItem<R, P>, string> | ((context: { item: PaginationItem<R, P> }) => unknown);
42
+ /**
43
+ * Keeps only this many pages loaded. Pages at the opposite end are dropped and can be fetched again.
44
+ */
45
+ maxPages?: number;
46
+ /**
47
+ * Transforms the list used by the component. The cache stays shared with other hooks.
48
+ */
49
+ select?: (context: { items: PaginationItem<R, P>[]; pages: ExtractResponseType<R>[] }) => TSelected;
50
+ /**
51
+ * Suspends until the first page arrives. Later pages never suspend.
52
+ */
53
+ suspense?: boolean;
54
+ /**
55
+ * Throws the error to the closest Error Boundary once the page request settles.
56
+ * Pass a function to decide per error.
57
+ */
58
+ throwOnError?: boolean | ((error: ExtractErrorType<R>) => boolean);
59
+ /**
60
+ * Refetches the loaded pages when any of these values change
61
+ */
62
+ dependencies?: any[];
63
+ /**
64
+ * Disables fetching
65
+ */
66
+ disabled?: boolean;
67
+ /**
68
+ * Rerenders only when the values used by the component change
69
+ */
70
+ dependencyTracking?: boolean;
71
+ /**
72
+ * Refetches pages restored from the cache on mount, even when they are not stale yet
73
+ */
74
+ revalidate?: boolean;
75
+ /**
76
+ * What is shown while a new list loads its first page:
77
+ *
78
+ * - "auto" (default) keeps the previous list when only query params changed, clears it for another resource
79
+ * - "preserve" always keeps the previous list
80
+ * - "clean" always clears it
81
+ */
82
+ keepPreviousData?: "auto" | "preserve" | "clean";
83
+ /**
84
+ * Refetches the loaded pages on an interval
85
+ */
86
+ refresh?: boolean;
87
+ /**
88
+ * Refresh interval time
89
+ */
90
+ refreshTime?: number;
91
+ /**
92
+ * Keeps refreshing while the tab is not focused
93
+ */
94
+ refetchBlurred?: boolean;
95
+ /**
96
+ * Refetches when the user leaves the tab
97
+ */
98
+ refetchOnBlur?: boolean;
99
+ /**
100
+ * Refetches when the user enters the tab
101
+ */
102
+ refetchOnFocus?: boolean;
103
+ /**
104
+ * Refetches when the network is restored
105
+ */
106
+ refetchOnReconnect?: boolean;
107
+ /**
108
+ * Keeps references of the unchanged parts of the list between updates
109
+ */
110
+ structuralSharing?: boolean;
111
+ /**
112
+ * Waits for the request to settle before starting a new list, for filters changing while typing
113
+ */
114
+ bounce?: boolean;
115
+ /**
116
+ * Bounce strategy
117
+ */
118
+ bounceType?: "debounce" | "throttle";
119
+ /**
120
+ * How long new lists are bounced
121
+ */
122
+ bounceTime?: number;
123
+ /**
124
+ * Only for the throttle strategy - handling of the last bounce event
125
+ */
126
+ bounceTimeout?: number;
127
+ };
128
+
129
+ export type UseInfiniteFetchConfigType = Partial<
130
+ Omit<UseInfiniteFetchOptionsType<RequestInstance, any, any>, "pagination" | "select" | "uniqueBy" | "maxPages">
131
+ >;
132
+
133
+ export type UseInfiniteFetchReturnType<
134
+ R extends RequestInstance,
135
+ P extends Pagination<R> = Pagination<R>,
136
+ TSelected = PaginationItem<R, P>[],
137
+ > = {
138
+ /** Items of all the loaded pages */
139
+ items: TSelected;
140
+ /** Response data of the loaded pages */
141
+ pages: ExtractResponseType<R>[];
142
+ /** Paging values of the loaded pages */
143
+ pageParams: unknown[];
144
+ /** Size of the whole list, when the pagination declares `total` */
145
+ total: number | null;
146
+ /** Another page can be fetched after the loaded ones */
147
+ hasNextPage: boolean;
148
+ /** Another page can be fetched before the loaded ones */
149
+ hasPreviousPage: boolean;
150
+ /** First page is loading and there is nothing to show yet */
151
+ loading: boolean;
152
+ /** Any page of this list is being fetched */
153
+ isFetching: boolean;
154
+ /** Loaded pages are being fetched again */
155
+ isRefetching: boolean;
156
+ isFetchingNextPage: boolean;
157
+ isFetchingPreviousPage: boolean;
158
+ /** Last attempt of fetching the next page failed */
159
+ isFetchNextPageError: boolean;
160
+ /** Last attempt of fetching the previous page failed */
161
+ isFetchPreviousPageError: boolean;
162
+ /** The list on screen belongs to the previous request, the new one is still loading */
163
+ isPreviousData: boolean;
164
+ /** Error of the last fetch */
165
+ error: ExtractErrorType<R> | null;
166
+ /** Status of the last response */
167
+ status: ExtractAdapterStatusType<ExtractAdapterType<R>> | null;
168
+ /** Additional data of the last response */
169
+ extra: ExtractAdapterExtraType<ExtractAdapterType<R>> | null;
170
+ /** Last fetch succeeded */
171
+ success: boolean;
172
+ /** Fetches the page after the loaded ones. Calls made while it loads share one request. */
173
+ fetchNextPage: () => Promise<InfinitePageResponse<R> | null>;
174
+ /** Fetches the page before the loaded ones. Calls made while it loads share one request. */
175
+ fetchPreviousPage: () => Promise<InfinitePageResponse<R> | null>;
176
+ /** Fetches all the loaded pages again and swaps the list when they arrive */
177
+ refetch: () => Promise<InfinitePageResponse<R> | null>;
178
+ /** Drops to the starting page and fetches it again */
179
+ reset: () => Promise<InfinitePageResponse<R> | null>;
180
+ /** Cancels every page being fetched by this list */
181
+ abort: () => void;
182
+ /** Called for every page that succeeded */
183
+ onSuccess: (callback: (event: InfinitePageEvent<R>) => void) => void;
184
+ /** Called for every page that failed */
185
+ onError: (callback: (event: InfinitePageEvent<R>) => void) => void;
186
+ /** Called for every finished page */
187
+ onFinished: (callback: (event: InfinitePageEvent<R>) => void) => void;
188
+ /** Called when the list starts over, for example to scroll back to the top */
189
+ onReset: (callback: () => void) => void;
190
+ /** State of the bounce used for new lists */
191
+ bounce: {
192
+ active: boolean;
193
+ reset: () => void;
194
+ };
195
+ };
@@ -0,0 +1,44 @@
1
+ import type { RequestInstance } from "@hyper-fetch/core";
2
+
3
+ /**
4
+ * Identity of a list. Everything describing the request takes part in it, so a changed filter, sort, page size
5
+ * or URL param starts a new list without anything having to be listed by hand.
6
+ */
7
+ export const getInfiniteKey = (request: RequestInstance, pagination: unknown, maxPages?: number) => {
8
+ return JSON.stringify([request.toJSON(), pagination, maxPages ?? null], (_key, value) => {
9
+ return typeof value === "function" ? value.toString() : value;
10
+ });
11
+ };
12
+
13
+ /**
14
+ * Keeps the first occurrence of every item
15
+ */
16
+ export const getUniqueItems = (items: unknown[], uniqueBy: unknown) => {
17
+ if (uniqueBy === undefined) {
18
+ return items;
19
+ }
20
+
21
+ const seen = new Set<unknown>();
22
+ return items.filter((item: any) => {
23
+ const identity = typeof uniqueBy === "function" ? uniqueBy({ item }) : item?.[uniqueBy as string];
24
+ if (seen.has(identity)) {
25
+ return false;
26
+ }
27
+ seen.add(identity);
28
+ return true;
29
+ });
30
+ };
31
+
32
+ /**
33
+ * Decides if the previous list stays on screen while the new one loads its first page
34
+ */
35
+ export const getShouldKeepPreviousList = (
36
+ mode: "auto" | "preserve" | "clean",
37
+ previous: RequestInstance,
38
+ current: RequestInstance,
39
+ ) => {
40
+ if (mode === "auto") {
41
+ return previous.method === current.method && previous.endpoint === current.endpoint;
42
+ }
43
+ return mode === "preserve";
44
+ };
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./hooks/use-fetch";
2
+ export * from "./hooks/use-infinite-fetch";
2
3
  export * from "./hooks/use-submit";
3
4
  export * from "./hooks/use-queue";
4
5
  export * from "./hooks/use-cache";
@@ -2,6 +2,7 @@ import type { RequestInstance } from "@hyper-fetch/core";
2
2
  import type { UseCacheOptionsType } from "hooks/use-cache";
3
3
  import type { UseEmitterOptionsType } from "hooks/use-emitter";
4
4
  import type { UseFetchOptionsType } from "hooks/use-fetch";
5
+ import type { UseInfiniteFetchConfigType } from "hooks/use-infinite-fetch";
5
6
  import type { UseListenerOptionsType } from "hooks/use-listener";
6
7
  import type { UseQueueOptionsType } from "hooks/use-queue";
7
8
  import type { UseSubmitOptionsType } from "hooks/use-submit";
@@ -13,6 +14,8 @@ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K>
13
14
  export type ProviderOptionsType = {
14
15
  // Selectors are component specific, they cannot be configured globally
15
16
  useFetchConfig?: Partial<DistributiveOmit<UseFetchOptionsType<RequestInstance>, "select">>;
17
+ // Pagination describes a single request, it is always passed to the hook
18
+ useInfiniteFetchConfig?: UseInfiniteFetchConfigType;
16
19
  useSubmitConfig?: Partial<DistributiveOmit<UseSubmitOptionsType<RequestInstance>, "select">>;
17
20
  useCacheConfig?: Partial<Omit<UseCacheOptionsType<RequestInstance>, "select">>;
18
21
  useQueueConfig?: Partial<UseQueueOptionsType>;
@@ -1,39 +0,0 @@
1
- import { createHttpMockingServer } from "@hyper-fetch/testing";
2
-
3
- import { client } from "../../utils";
4
-
5
- const { resetMocks, startServer, stopServer } = createHttpMockingServer();
6
-
7
- describe("useFetch [ Infinite ]", () => {
8
- beforeAll(() => {
9
- startServer();
10
- });
11
-
12
- afterEach(() => {
13
- resetMocks();
14
- });
15
-
16
- afterAll(() => {
17
- stopServer();
18
- });
19
-
20
- beforeEach(() => {
21
- vi.resetModules();
22
- client.clear();
23
- });
24
-
25
- describe("when request query params are changed", () => {
26
- it("should allow to cancel previous request on switching pages during requests", async () => {
27
- // TODO
28
- });
29
- it("should use cached pages on mounting", async () => {
30
- // TODO
31
- });
32
- it("should automatically generate request cacheKey for paginated views", async () => {
33
- // TODO
34
- });
35
- it("should not remove previous page data until current is fetched", async () => {
36
- // TODO
37
- });
38
- });
39
- });