@hyper-fetch/react 9.6.1 → 9.7.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 (98) hide show
  1. package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +1 -1
  2. package/__tests__/features/helpers/use-tracked-state/use-tracked-state.keys.spec.ts +294 -0
  3. package/__tests__/features/helpers/utils.spec.ts +127 -0
  4. package/__tests__/features/provider/provider.config.spec.tsx +172 -0
  5. package/__tests__/features/use-app-manager/use-app-manager.events.spec.tsx +497 -0
  6. package/__tests__/features/use-cache/use-cache.state.spec.tsx +326 -0
  7. package/__tests__/features/use-emitter/use-emitter.lifecycle.spec.tsx +417 -0
  8. package/__tests__/features/use-fetch/use-fetch.bounce-timers.spec.ts +199 -0
  9. package/__tests__/features/use-fetch/use-fetch.cache-events.spec.ts +212 -0
  10. package/__tests__/features/use-fetch/use-fetch.callbacks.spec.tsx +359 -0
  11. package/__tests__/features/use-fetch/use-fetch.hydration.spec.tsx +126 -0
  12. package/__tests__/features/use-fetch/use-fetch.infinite.spec.ts +146 -0
  13. package/__tests__/features/use-fetch/use-fetch.initial-state.spec.ts +340 -0
  14. package/__tests__/features/use-fetch/use-fetch.keys.spec.tsx +559 -0
  15. package/__tests__/features/use-fetch/use-fetch.lifecycle.spec.ts +348 -0
  16. package/__tests__/features/use-fetch/use-fetch.mounting.spec.tsx +411 -0
  17. package/__tests__/features/use-fetch/use-fetch.pagination.spec.ts +177 -0
  18. package/__tests__/features/use-fetch/use-fetch.refresh-interval.spec.ts +355 -0
  19. package/__tests__/features/use-fetch/use-fetch.response-order.spec.ts +105 -0
  20. package/__tests__/features/use-fetch/use-fetch.retry.spec.ts +235 -0
  21. package/__tests__/features/use-fetch/use-fetch.return-types.spec.ts +186 -0
  22. package/__tests__/features/use-fetch/use-fetch.scope.spec.ts +333 -0
  23. package/__tests__/features/use-fetch/use-fetch.ssr.spec.tsx +195 -0
  24. package/__tests__/features/use-fetch/use-fetch.suspense-edge.spec.tsx +391 -0
  25. package/__tests__/features/use-fetch/use-fetch.throwing-callbacks.spec.tsx +112 -0
  26. package/__tests__/features/use-fetch/use-fetch.tracking.spec.tsx +364 -0
  27. package/__tests__/features/use-fetch/use-fetch.window-events.spec.ts +300 -0
  28. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.parity.spec.tsx +1027 -0
  29. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.resubscribe.spec.tsx +267 -0
  30. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +64 -1
  31. package/__tests__/features/use-is-fetching/use-is-fetching.lifecycle.spec.tsx +301 -0
  32. package/__tests__/features/use-listener/use-listener.lifecycle.spec.tsx +507 -0
  33. package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +89 -0
  34. package/__tests__/features/use-queue/use-queue.controls.spec.tsx +593 -0
  35. package/__tests__/features/use-queue/use-queue.list.spec.tsx +560 -0
  36. package/__tests__/features/use-queue/use-queue.progress.spec.tsx +650 -0
  37. package/__tests__/features/use-submit/use-submit.abort.spec.tsx +270 -0
  38. package/__tests__/features/use-submit/use-submit.actions.spec.tsx +446 -0
  39. package/__tests__/features/use-submit/use-submit.arguments.spec.tsx +732 -0
  40. package/__tests__/features/use-submit/use-submit.bounce.spec.tsx +644 -0
  41. package/__tests__/features/use-submit/use-submit.callbacks.spec.tsx +860 -0
  42. package/__tests__/features/use-submit/use-submit.chaining.spec.tsx +167 -0
  43. package/__tests__/features/use-submit/use-submit.double-submit.spec.tsx +552 -0
  44. package/__tests__/features/use-submit/use-submit.offline.spec.tsx +285 -0
  45. package/__tests__/features/use-submit/use-submit.optimistic-cache.spec.tsx +619 -0
  46. package/__tests__/features/use-submit/use-submit.optimistic-helpers.spec.tsx +455 -0
  47. package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +6 -0
  48. package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
  49. package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
  50. package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
  51. package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
  52. package/__tests__/utils/gate.utils.ts +103 -0
  53. package/__tests__/utils/gated-client.utils.ts +158 -0
  54. package/__tests__/utils/helpers.utils.ts +19 -0
  55. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
  56. package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
  57. package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
  58. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
  59. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
  60. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
  61. package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
  62. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
  63. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
  64. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
  65. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
  66. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
  67. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
  68. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
  69. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
  70. package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
  71. package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
  72. package/dist/hooks/use-submit/use-submit.constants.d.ts +1 -1
  73. package/dist/hooks/use-submit/use-submit.constants.d.ts.map +1 -1
  74. package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
  75. package/dist/hooks/use-submit/use-submit.types.d.ts +6 -1
  76. package/dist/hooks/use-submit/use-submit.types.d.ts.map +1 -1
  77. package/dist/index.mjs +633 -346
  78. package/dist/index.mjs.map +1 -1
  79. package/dist/provider/provider.d.ts.map +1 -1
  80. package/package.json +1 -1
  81. package/src/helpers/use-request-events/use-request-events.hooks.ts +141 -28
  82. package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
  83. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
  84. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
  85. package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
  86. package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
  87. package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
  88. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
  89. package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
  90. package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
  91. package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
  92. package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
  93. package/src/hooks/use-submit/use-submit.constants.ts +3 -1
  94. package/src/hooks/use-submit/use-submit.hooks.ts +167 -53
  95. package/src/hooks/use-submit/use-submit.types.ts +6 -0
  96. package/src/provider/provider.tsx +9 -1
  97. package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
  98. package/__tests__/features/use-fetch/use-fetch.retry.ts +0 -38
@@ -0,0 +1,195 @@
1
+ // @vitest-environment node
2
+ import type { RequestInstance } from "@hyper-fetch/core";
3
+ import { Client } from "@hyper-fetch/core";
4
+ import { useCache } from "hooks/use-cache";
5
+ import type { UseFetchOptionsType } from "hooks/use-fetch";
6
+ import { useFetch } from "hooks/use-fetch";
7
+ import { useIsFetching } from "hooks/use-is-fetching";
8
+ import { Provider } from "provider";
9
+ import { Suspense } from "react";
10
+ import { renderToString } from "react-dom/server";
11
+
12
+ type User = { id: number; name: string };
13
+
14
+ const user: User = { id: 1, name: "Maciej" };
15
+
16
+ const countListeners = (client: Client) => {
17
+ return [client.requestManager.emitter, client.cache.emitter, client.fetchDispatcher.emitter].reduce(
18
+ (sum, emitter) => sum + emitter.eventNames().reduce((count, name) => count + emitter.listenerCount(name), 0),
19
+ 0,
20
+ );
21
+ };
22
+
23
+ /**
24
+ * Server rendering - there is no window, effects never run and nothing can be left behind after the render
25
+ */
26
+ describe("useFetch [ Server Side Rendering ]", () => {
27
+ let client = new Client({ url: "http://localhost" });
28
+ let request = client.createRequest<{ response: User }>()({ endpoint: "/users/1" });
29
+ let mock = vi.fn();
30
+
31
+ const Page = <T extends RequestInstance>({ req, options }: { req: T; options?: UseFetchOptionsType<T> }) => {
32
+ const { data, loading, error, success } = useFetch(req, options);
33
+ return <div>{JSON.stringify({ data, loading, error, success })}</div>;
34
+ };
35
+
36
+ const readMarkup = (markup: string) => {
37
+ const json = markup.replaceAll(/<[^>]+>/g, "").replaceAll("&quot;", '"');
38
+ return JSON.parse(json);
39
+ };
40
+
41
+ const saveScopedResponse = (scope: string) => {
42
+ const scoped = request.setScope(scope);
43
+ client.cache.set(scoped, {
44
+ data: user,
45
+ error: null,
46
+ status: 200,
47
+ success: true,
48
+ extra: client.adapter.defaultExtra,
49
+ requestTimestamp: Date.now(),
50
+ responseTimestamp: Date.now(),
51
+ addedTimestamp: Date.now(),
52
+ triggerTimestamp: Date.now(),
53
+ retries: 0,
54
+ isCanceled: false,
55
+ isOffline: false,
56
+ willRetry: false,
57
+ });
58
+ return scoped;
59
+ };
60
+
61
+ beforeEach(() => {
62
+ vi.useFakeTimers();
63
+ client = new Client({ url: "http://localhost" });
64
+ mock = vi.fn(() => ({ data: user, status: 200 }));
65
+ request = client.createRequest<{ response: User }>()({ endpoint: "/users/1" }).setMock(mock);
66
+ });
67
+
68
+ afterEach(() => {
69
+ vi.useRealTimers();
70
+ });
71
+
72
+ it("should run without the window", () => {
73
+ expect(typeof window).toBe("undefined");
74
+ expect(client.mode).toBe("server");
75
+ });
76
+
77
+ describe("when there is no data", () => {
78
+ it("should render the loading state", () => {
79
+ const markup = renderToString(<Page req={request} />);
80
+
81
+ expect(readMarkup(markup)).toStrictEqual({ data: null, loading: true, error: null, success: false });
82
+ });
83
+ it("should not send any request", async () => {
84
+ renderToString(<Page req={request} />);
85
+ await vi.advanceTimersByTimeAsync(1000);
86
+
87
+ expect(mock).not.toHaveBeenCalled();
88
+ expect(client.fetchDispatcher.getAllRunningRequests()).toHaveLength(0);
89
+ expect(client.fetchDispatcher.getQueuesKeys()).toHaveLength(0);
90
+ });
91
+ it("should not leave any timers", () => {
92
+ renderToString(
93
+ <Page req={request} options={{ refresh: true, refreshTime: 1000, bounce: true, dependencies: [1] }} />,
94
+ );
95
+
96
+ expect(vi.getTimerCount()).toBe(0);
97
+ });
98
+ it("should not leave any listeners", () => {
99
+ const baseline = countListeners(client);
100
+
101
+ renderToString(<Page req={request} />);
102
+
103
+ expect(countListeners(client)).toBe(baseline);
104
+ });
105
+ it("should render the idle state when disabled", () => {
106
+ const markup = renderToString(<Page req={request} options={{ disabled: true }} />);
107
+
108
+ expect(readMarkup(markup)).toStrictEqual({ data: null, loading: false, error: null, success: false });
109
+ });
110
+ it("should render the same markup every time", () => {
111
+ const first = renderToString(<Page req={request} />);
112
+ const second = renderToString(<Page req={request} />);
113
+
114
+ expect(second).toBe(first);
115
+ });
116
+ });
117
+
118
+ describe("when the data is available", () => {
119
+ it("should render the initial response", () => {
120
+ const markup = renderToString(<Page req={request} options={{ initialResponse: { data: user } }} />);
121
+
122
+ expect(readMarkup(markup).data).toStrictEqual(user);
123
+ expect(readMarkup(markup).success).toBeTrue();
124
+ });
125
+ it("should render the data cached for the scope of the request", () => {
126
+ const scoped = saveScopedResponse("session-1");
127
+
128
+ const markup = renderToString(<Page req={scoped} options={{ revalidate: false }} />);
129
+
130
+ expect(readMarkup(markup)).toStrictEqual({ data: user, loading: false, error: null, success: true });
131
+ });
132
+ it("should not render the data of another scope", () => {
133
+ saveScopedResponse("session-1");
134
+
135
+ const markup = renderToString(<Page req={request.setScope("session-2")} options={{ revalidate: false }} />);
136
+
137
+ expect(readMarkup(markup).data).toBeNull();
138
+ });
139
+ it("should render the data fetched on the server before rendering", async () => {
140
+ const scoped = request.setScope("session-1");
141
+ const sending = scoped.send();
142
+ await vi.advanceTimersByTimeAsync(1000);
143
+ await sending;
144
+
145
+ const markup = renderToString(<Page req={scoped} />);
146
+
147
+ expect(readMarkup(markup).data).toStrictEqual(user);
148
+ expect(mock).toHaveBeenCalledOnce();
149
+ });
150
+ it("should apply the selector", () => {
151
+ const scoped = saveScopedResponse("session-1");
152
+ const Name = () => {
153
+ const { data } = useFetch(scoped, { select: (value) => value.name });
154
+ return <div>{data}</div>;
155
+ };
156
+
157
+ expect(renderToString(<Name />)).toContain("Maciej");
158
+ });
159
+ });
160
+
161
+ describe("when other hooks are rendered on the server", () => {
162
+ it("should render the cached data with useCache", () => {
163
+ const scoped = saveScopedResponse("session-1");
164
+ const Cached = () => <div>{useCache(scoped).data?.name}</div>;
165
+
166
+ expect(renderToString(<Cached />)).toContain("Maciej");
167
+ });
168
+ it("should render zero running requests with useIsFetching", () => {
169
+ const Counter = () => <div>{useIsFetching(client)}</div>;
170
+
171
+ expect(renderToString(<Counter />)).toBe("<div>0</div>");
172
+ });
173
+ it("should read the provider config", () => {
174
+ const markup = renderToString(
175
+ <Provider config={{ useFetchConfig: { disabled: true } }}>
176
+ <Page req={request} />
177
+ </Provider>,
178
+ );
179
+
180
+ expect(readMarkup(markup).loading).toBeFalse();
181
+ });
182
+ it("should render the suspense fallback for the missing data", () => {
183
+ const Suspended = () => <div>{useFetch(request, { suspense: true }).data?.name}</div>;
184
+
185
+ const markup = renderToString(
186
+ <Suspense fallback={<span>fallback</span>}>
187
+ <Suspended />
188
+ </Suspense>,
189
+ );
190
+
191
+ expect(markup).toContain("fallback");
192
+ expect(markup).not.toContain("Maciej");
193
+ });
194
+ });
195
+ });
@@ -0,0 +1,391 @@
1
+ import type { RequestInstance } from "@hyper-fetch/core";
2
+ import { Client } from "@hyper-fetch/core";
3
+ import { act, render, screen } from "@testing-library/react";
4
+ import { useFetch } from "hooks/use-fetch";
5
+ import type { ReactNode } from "react";
6
+ import { Component, StrictMode, Suspense } from "react";
7
+
8
+ import { client, createRequest } from "../../utils";
9
+ import { advance, gateRequest, setCacheResponse, settle } from "../../utils/gate.utils";
10
+
11
+ class ErrorBoundary extends Component<{ children: ReactNode }, { error: Error | null }> {
12
+ constructor(props: { children: ReactNode }) {
13
+ super(props);
14
+ this.state = { error: null };
15
+ }
16
+
17
+ static getDerivedStateFromError(error: Error) {
18
+ return { error };
19
+ }
20
+
21
+ handleReset = () => {
22
+ // oxlint-disable-next-line react/no-set-state -- error boundaries have to be class components
23
+ this.setState({ error: null });
24
+ };
25
+
26
+ render() {
27
+ const { error } = this.state;
28
+ if (error) {
29
+ return (
30
+ <button type="button" data-testid="boundary" onClick={this.handleReset}>
31
+ {error.message}
32
+ </button>
33
+ );
34
+ }
35
+ return this.props.children;
36
+ }
37
+ }
38
+
39
+ const Page = ({
40
+ request,
41
+ name = "page",
42
+ throwOnError = false,
43
+ }: {
44
+ request: RequestInstance;
45
+ name?: string;
46
+ throwOnError?: boolean;
47
+ }) => {
48
+ const { data, error, loading, success } = useFetch(request, { suspense: true, throwOnError });
49
+ return <div data-testid={name}>{JSON.stringify({ data, error: error?.message ?? null, loading, success })}</div>;
50
+ };
51
+
52
+ const Fallback = ({ name = "fallback" }: { name?: string }) => <div data-testid={name}>loading</div>;
53
+
54
+ const read = (name = "page") => JSON.parse(screen.getByTestId(name).textContent || "{}");
55
+
56
+ describe("useFetch [ Suspense Edge Cases ]", () => {
57
+ let request = createRequest<{ value: number } | null>();
58
+ let calls = gateRequest(request);
59
+
60
+ beforeEach(() => {
61
+ vi.useFakeTimers();
62
+ client.clear();
63
+ request = createRequest<{ value: number } | null>();
64
+ calls = gateRequest(request);
65
+ vi.spyOn(console, "error").mockImplementation(() => null);
66
+ });
67
+
68
+ afterEach(() => {
69
+ vi.restoreAllMocks();
70
+ vi.useRealTimers();
71
+ });
72
+
73
+ describe("when the request resolves", () => {
74
+ it("should send a single request for the suspended component", async () => {
75
+ render(
76
+ <Suspense fallback={<Fallback />}>
77
+ <Page request={request} />
78
+ </Suspense>,
79
+ );
80
+ await advance();
81
+ calls[0].succeed({ value: 1 });
82
+ await settle();
83
+ await advance(5000);
84
+
85
+ expect(read().data).toStrictEqual({ value: 1 });
86
+ expect(calls).toHaveLength(1);
87
+ });
88
+ it("should not be in the loading state after resolving", async () => {
89
+ render(
90
+ <Suspense fallback={<Fallback />}>
91
+ <Page request={request} />
92
+ </Suspense>,
93
+ );
94
+ await advance();
95
+ calls[0].succeed({ value: 1 });
96
+ await settle();
97
+
98
+ expect(read()).toStrictEqual({ data: { value: 1 }, error: null, loading: false, success: true });
99
+ });
100
+ it("should send a single request for many components using the same request", async () => {
101
+ render(
102
+ <Suspense fallback={<Fallback />}>
103
+ <Page request={request} name="first" />
104
+ <Page request={request} name="second" />
105
+ <Page request={request} name="third" />
106
+ </Suspense>,
107
+ );
108
+ await advance();
109
+ calls[0].succeed({ value: 1 });
110
+ await settle();
111
+ await advance(5000);
112
+
113
+ expect(read("first").data).toStrictEqual({ value: 1 });
114
+ expect(read("second").data).toStrictEqual({ value: 1 });
115
+ expect(read("third").data).toStrictEqual({ value: 1 });
116
+ expect(calls).toHaveLength(1);
117
+ });
118
+ it("should send a single request in StrictMode", async () => {
119
+ render(
120
+ <StrictMode>
121
+ <Suspense fallback={<Fallback />}>
122
+ <Page request={request} />
123
+ </Suspense>
124
+ </StrictMode>,
125
+ );
126
+ await advance();
127
+ calls[0].succeed({ value: 1 });
128
+ await settle();
129
+ await advance(5000);
130
+
131
+ expect(read().data).toStrictEqual({ value: 1 });
132
+ expect(calls).toHaveLength(1);
133
+ });
134
+ it("should finish suspending when the response has no data", async () => {
135
+ render(
136
+ <Suspense fallback={<Fallback />}>
137
+ <Page request={request} />
138
+ </Suspense>,
139
+ );
140
+ await advance();
141
+ calls[0].succeed(null, 204);
142
+ await settle();
143
+ await settle();
144
+
145
+ expect(read()).toStrictEqual({ data: null, error: null, loading: false, success: true });
146
+ expect(calls).toHaveLength(1);
147
+ });
148
+ it("should render the error response once and not request again", async () => {
149
+ render(
150
+ <Suspense fallback={<Fallback />}>
151
+ <Page request={request} />
152
+ </Suspense>,
153
+ );
154
+ await advance();
155
+ calls[0].fail(new Error("Failed"));
156
+ await settle();
157
+ await advance(5000);
158
+
159
+ expect(read()).toStrictEqual({ data: null, error: "Failed", loading: false, success: false });
160
+ expect(calls).toHaveLength(1);
161
+ });
162
+ });
163
+
164
+ describe("when the cache has data", () => {
165
+ it("should revalidate cached data that was not fetched by the suspended component", async () => {
166
+ setCacheResponse(request, { value: 1 });
167
+ await advance(5000);
168
+
169
+ render(
170
+ <Suspense fallback={<Fallback />}>
171
+ <Page request={request} />
172
+ </Suspense>,
173
+ );
174
+ await advance();
175
+
176
+ expect(screen.queryByTestId("fallback")).toBeNull();
177
+ expect(read().data).toStrictEqual({ value: 1 });
178
+ expect(calls).toHaveLength(1);
179
+ });
180
+ });
181
+
182
+ describe("when the suspended component is gone before the response", () => {
183
+ it("should not reuse the outdated response on the next mount", async () => {
184
+ const view = render(
185
+ <Suspense fallback={<Fallback />}>
186
+ <Page request={request} />
187
+ </Suspense>,
188
+ );
189
+ await advance();
190
+ view.unmount();
191
+ calls[0].fail(new Error("Old failure"));
192
+ await settle();
193
+
194
+ // User comes back after a while
195
+ await advance(60_000);
196
+ render(
197
+ <Suspense fallback={<Fallback />}>
198
+ <Page request={request} />
199
+ </Suspense>,
200
+ );
201
+ await advance();
202
+
203
+ expect(screen.getByTestId("fallback")).toBeInTheDocument();
204
+ expect(calls).toHaveLength(2);
205
+
206
+ calls[1].succeed({ value: 2 });
207
+ await settle();
208
+
209
+ expect(read()).toStrictEqual({ data: { value: 2 }, error: null, loading: false, success: true });
210
+ });
211
+ });
212
+
213
+ describe("when two clients use the same endpoint", () => {
214
+ const createClients = () => {
215
+ const clientA = new Client({ url: "http://a.test" });
216
+ const clientB = new Client({ url: "http://b.test" });
217
+ const requestA = clientA.createRequest<{ response: string }>()({ endpoint: "/same" });
218
+ const requestB = clientB.createRequest<{ response: string }>()({ endpoint: "/same" });
219
+ return { requestA, requestB, callsA: gateRequest(requestA), callsB: gateRequest(requestB) };
220
+ };
221
+
222
+ it("should not give the response of one client to the other", async () => {
223
+ const { requestA, requestB, callsA, callsB } = createClients();
224
+ const viewA = render(
225
+ <Suspense fallback={<Fallback name="fallback-a" />}>
226
+ <Page request={requestA} name="a" />
227
+ </Suspense>,
228
+ );
229
+ await advance();
230
+ render(
231
+ <Suspense fallback={<Fallback name="fallback-b" />}>
232
+ <Page request={requestB} name="b" />
233
+ </Suspense>,
234
+ );
235
+ await advance();
236
+
237
+ viewA.unmount();
238
+ callsA[0].succeed("data-a");
239
+ await settle();
240
+
241
+ expect(screen.queryByTestId("b")).toBeNull();
242
+ expect(screen.getByTestId("fallback-b")).toBeInTheDocument();
243
+
244
+ callsB[0].succeed("data-b");
245
+ await settle();
246
+
247
+ expect(read("b").data).toBe("data-b");
248
+ });
249
+ it("should resolve each client with its own response", async () => {
250
+ const { requestA, requestB, callsA, callsB } = createClients();
251
+ render(
252
+ <>
253
+ <Suspense fallback={<Fallback name="fallback-a" />}>
254
+ <Page request={requestA} name="a" />
255
+ </Suspense>
256
+ <Suspense fallback={<Fallback name="fallback-b" />}>
257
+ <Page request={requestB} name="b" />
258
+ </Suspense>
259
+ </>,
260
+ );
261
+ await advance();
262
+
263
+ callsB[0].succeed("data-b");
264
+ await settle();
265
+ expect(read("b").data).toBe("data-b");
266
+ expect(screen.getByTestId("fallback-a")).toBeInTheDocument();
267
+
268
+ callsA[0].succeed("data-a");
269
+ await settle();
270
+ expect(read("a").data).toBe("data-a");
271
+ });
272
+ });
273
+
274
+ describe("when two scopes use the same request", () => {
275
+ it("should resolve each scope with its own response", async () => {
276
+ const scopedA = request.setScope("a");
277
+ const scopedB = request.setScope("b");
278
+ render(
279
+ <>
280
+ <Suspense fallback={<Fallback name="fallback-a" />}>
281
+ <Page request={scopedA} name="a" />
282
+ </Suspense>
283
+ <Suspense fallback={<Fallback name="fallback-b" />}>
284
+ <Page request={scopedB} name="b" />
285
+ </Suspense>
286
+ </>,
287
+ );
288
+ await advance();
289
+ expect(calls).toHaveLength(2);
290
+
291
+ calls.find((call) => call.request.scope === "b")?.succeed({ value: 2 });
292
+ await settle();
293
+
294
+ expect(read("b").data).toStrictEqual({ value: 2 });
295
+ expect(screen.getByTestId("fallback-a")).toBeInTheDocument();
296
+
297
+ calls.find((call) => call.request.scope === "a")?.succeed({ value: 1 });
298
+ await settle();
299
+
300
+ expect(read("a").data).toStrictEqual({ value: 1 });
301
+ });
302
+ });
303
+
304
+ describe("when the key changes", () => {
305
+ it("should suspend again without rendering the previous resource", async () => {
306
+ const userRequest = createRequest<{ id: number }, any, "/users/:id">({ endpoint: "/users/:id" });
307
+ const userCalls = gateRequest(userRequest);
308
+ const rendered: { id: number; dataId: number | undefined }[] = [];
309
+ const User = ({ id }: { id: number }) => {
310
+ const { data } = useFetch(userRequest.setParams({ id }), { suspense: true });
311
+ rendered.push({ id, dataId: data?.id });
312
+ return <div data-testid="user">{data?.id}</div>;
313
+ };
314
+ const view = render(
315
+ <Suspense fallback={<Fallback />}>
316
+ <User id={1} />
317
+ </Suspense>,
318
+ );
319
+ await advance();
320
+ userCalls[0].succeed({ id: 1 });
321
+ await settle();
322
+ expect(screen.getByTestId("user").textContent).toBe("1");
323
+
324
+ view.rerender(
325
+ <Suspense fallback={<Fallback />}>
326
+ <User id={2} />
327
+ </Suspense>,
328
+ );
329
+ await advance();
330
+ expect(screen.getByTestId("fallback")).toBeInTheDocument();
331
+
332
+ userCalls[1].succeed({ id: 2 });
333
+ await settle();
334
+
335
+ expect(screen.getByTestId("user").textContent).toBe("2");
336
+ expect(rendered.filter((item) => item.id !== item.dataId)).toStrictEqual([]);
337
+ });
338
+ });
339
+
340
+ describe("when combined with the error boundary", () => {
341
+ it("should throw the error, and fetch again after the boundary reset", async () => {
342
+ render(
343
+ <ErrorBoundary>
344
+ <Suspense fallback={<Fallback />}>
345
+ <Page request={request} throwOnError />
346
+ </Suspense>
347
+ </ErrorBoundary>,
348
+ );
349
+ await advance();
350
+ calls[0].fail(new Error("Failed"));
351
+ await settle();
352
+
353
+ expect(screen.getByTestId("boundary").textContent).toBe("Failed");
354
+ expect(calls).toHaveLength(1);
355
+
356
+ act(() => {
357
+ screen.getByTestId("boundary").click();
358
+ });
359
+ await advance();
360
+
361
+ expect(screen.getByTestId("fallback")).toBeInTheDocument();
362
+ expect(calls).toHaveLength(2);
363
+
364
+ calls[1].succeed({ value: 1 });
365
+ await settle();
366
+
367
+ expect(read()).toStrictEqual({ data: { value: 1 }, error: null, loading: false, success: true });
368
+ });
369
+ it("should throw again when the request fails again after the reset", async () => {
370
+ render(
371
+ <ErrorBoundary>
372
+ <Suspense fallback={<Fallback />}>
373
+ <Page request={request} throwOnError />
374
+ </Suspense>
375
+ </ErrorBoundary>,
376
+ );
377
+ await advance();
378
+ calls[0].fail(new Error("First"));
379
+ await settle();
380
+
381
+ act(() => {
382
+ screen.getByTestId("boundary").click();
383
+ });
384
+ await advance();
385
+ calls[1].fail(new Error("Second"));
386
+ await settle();
387
+
388
+ expect(screen.getByTestId("boundary").textContent).toBe("Second");
389
+ });
390
+ });
391
+ });
@@ -0,0 +1,112 @@
1
+ import { act, renderHook, waitFor } from "@testing-library/react";
2
+ import { useFetch } from "hooks/use-fetch";
3
+
4
+ import { createGatedClient } from "../../utils/gated-client.utils";
5
+ import { collectThrownErrors } from "../../utils/helpers.utils";
6
+
7
+ type User = { id: number };
8
+
9
+ /**
10
+ * Callbacks of a hook run inside of the request lifecycle, next to the listeners of other hooks. A throwing one
11
+ * can't keep the response from the other hooks - its error is thrown outside of the lifecycle instead.
12
+ */
13
+ describe("useFetch [ Throwing callbacks ]", () => {
14
+ const failure = new Error("Callback failed");
15
+ const fail = () => {
16
+ throw failure;
17
+ };
18
+
19
+ const setup = () => {
20
+ const gated = createGatedClient();
21
+ const request = gated.client.createRequest<{ response: User }>()({ endpoint: "/users/1" });
22
+ return { ...gated, request };
23
+ };
24
+
25
+ it.each(["onSuccess", "onFinished", "onRequestStart", "onResponseStart"] as const)(
26
+ "should still give the data to the other hooks when %s of one of them throws",
27
+ async (name) => {
28
+ const thrown = collectThrownErrors();
29
+ const { request, waitForCall } = setup();
30
+ const onSuccess = vi.fn();
31
+ const failing = renderHook(() => {
32
+ const state = useFetch(request, { dependencyTracking: false });
33
+ state[name](fail);
34
+ return state;
35
+ });
36
+ const other = renderHook(() => {
37
+ const state = useFetch(request, { dependencyTracking: false });
38
+ state.onSuccess(onSuccess);
39
+ return state;
40
+ });
41
+ const call = await waitForCall(0);
42
+
43
+ act(() => {
44
+ call.succeed({ id: 1 });
45
+ });
46
+
47
+ await waitFor(() => {
48
+ expect(other.result.current.data).toStrictEqual({ id: 1 });
49
+ });
50
+ expect(failing.result.current.data).toStrictEqual({ id: 1 });
51
+ expect(other.result.current.loading).toBeFalse();
52
+ expect(onSuccess).toHaveBeenCalledTimes(1);
53
+ await waitFor(() => {
54
+ expect(thrown).toStrictEqual([failure]);
55
+ });
56
+ },
57
+ );
58
+
59
+ it("should still call the error callback of the other hooks when onError of one of them throws", async () => {
60
+ const thrown = collectThrownErrors();
61
+ const { request, waitForCall } = setup();
62
+ const onError = vi.fn();
63
+ renderHook(() => useFetch(request, { dependencyTracking: false }).onError(fail));
64
+ const other = renderHook(() => {
65
+ const state = useFetch(request, { dependencyTracking: false });
66
+ state.onError(onError);
67
+ return state;
68
+ });
69
+ const call = await waitForCall(0);
70
+
71
+ act(() => {
72
+ call.fail({ message: "Nope" }, 400);
73
+ });
74
+
75
+ await waitFor(() => {
76
+ expect(onError).toHaveBeenCalledTimes(1);
77
+ });
78
+ expect(other.result.current.error).toStrictEqual({ message: "Nope" });
79
+ await waitFor(() => {
80
+ expect(thrown).toStrictEqual([failure]);
81
+ });
82
+ });
83
+
84
+ it("should fetch again after a callback threw", async () => {
85
+ collectThrownErrors();
86
+ const { request, waitForCall } = setup();
87
+ const { result } = renderHook(() => {
88
+ const state = useFetch(request, { dependencyTracking: false });
89
+ state.onSuccess(fail);
90
+ return state;
91
+ });
92
+ const first = await waitForCall(0);
93
+ act(() => {
94
+ first.succeed({ id: 1 });
95
+ });
96
+ await waitFor(() => {
97
+ expect(result.current.loading).toBeFalse();
98
+ });
99
+
100
+ act(() => {
101
+ result.current.refetch();
102
+ });
103
+ const second = await waitForCall(1);
104
+ act(() => {
105
+ second.succeed({ id: 2 });
106
+ });
107
+
108
+ await waitFor(() => {
109
+ expect(result.current.data).toStrictEqual({ id: 2 });
110
+ });
111
+ });
112
+ });