@hyper-fetch/react 9.6.1 → 9.6.2

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 (91) 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-settlement.spec.ts +6 -0
  47. package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
  48. package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
  49. package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
  50. package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
  51. package/__tests__/utils/gate.utils.ts +103 -0
  52. package/__tests__/utils/gated-client.utils.ts +158 -0
  53. package/__tests__/utils/helpers.utils.ts +19 -0
  54. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
  55. package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
  56. package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
  57. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
  58. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
  59. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
  60. package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
  61. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
  62. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
  63. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
  64. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
  65. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
  66. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
  67. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
  68. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
  69. package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
  70. package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
  71. package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
  72. package/dist/index.mjs +630 -346
  73. package/dist/index.mjs.map +1 -1
  74. package/dist/provider/provider.d.ts.map +1 -1
  75. package/package.json +1 -1
  76. package/src/helpers/use-request-events/use-request-events.hooks.ts +141 -28
  77. package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
  78. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
  79. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
  80. package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
  81. package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
  82. package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
  83. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
  84. package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
  85. package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
  86. package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
  87. package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
  88. package/src/hooks/use-submit/use-submit.hooks.ts +163 -53
  89. package/src/provider/provider.tsx +9 -1
  90. package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
  91. package/__tests__/features/use-fetch/use-fetch.retry.ts +0 -38
@@ -0,0 +1,186 @@
1
+ import type { Client, ExtractAdapterExtraType, ExtractAdapterType } from "@hyper-fetch/core";
2
+ import type { UseCacheReturnType } from "hooks/use-cache";
3
+ import type { UseFetchOptionsType, UseFetchReturnType } from "hooks/use-fetch";
4
+ import { useFetch } from "hooks/use-fetch";
5
+ import { expectTypeOf } from "vitest";
6
+
7
+ import { client } from "../../utils";
8
+
9
+ type User = { id: number; name: string; tags: string[] };
10
+ type ApiError = { code: string; message: string };
11
+
12
+ const getUser = client.createRequest<{ response: User; error: ApiError }>()({ endpoint: "/users/:userId" });
13
+ const getUsers = client.createRequest<{ response: User[]; queryParams: { page: number } }>()({ endpoint: "/users" });
14
+ const getPlain = client.createRequest<{ response: string }>()({ endpoint: "/plain" });
15
+
16
+ const userRequest = getUser.setParams({ userId: 1 });
17
+
18
+ type UserRequest = typeof userRequest;
19
+ type UserState = UseFetchReturnType<UserRequest>;
20
+
21
+ /**
22
+ * Type level tests - nothing is rendered, hooks are referenced only inside of never called functions
23
+ */
24
+ describe("useFetch [ Return Types ]", () => {
25
+ describe("state", () => {
26
+ it("should type data as the response or null", () => {
27
+ expectTypeOf<UserState["data"]>().toEqualTypeOf<User | null>();
28
+ expectTypeOf<UseFetchReturnType<typeof getUsers>["data"]>().toEqualTypeOf<User[] | null>();
29
+ expectTypeOf<UseFetchReturnType<typeof getPlain>["data"]>().toEqualTypeOf<string | null>();
30
+ });
31
+ it("should type error as the request error union or null", () => {
32
+ expectTypeOf<UserState["error"]>().toEqualTypeOf<ApiError | Error | null>();
33
+ expectTypeOf<UseFetchReturnType<typeof getPlain>["error"]>().toEqualTypeOf<Error | null>();
34
+ });
35
+ it("should type the flags, counters and timestamps", () => {
36
+ expectTypeOf<UserState["loading"]>().toEqualTypeOf<boolean>();
37
+ expectTypeOf<UserState["success"]>().toEqualTypeOf<boolean>();
38
+ expectTypeOf<UserState["retries"]>().toEqualTypeOf<number>();
39
+ expectTypeOf<UserState["responseTimestamp"]>().toEqualTypeOf<Date | null>();
40
+ expectTypeOf<UserState["requestTimestamp"]>().toEqualTypeOf<Date | null>();
41
+ });
42
+ it("should type status and extra with the adapter types", () => {
43
+ expectTypeOf<UserState["status"]>().toEqualTypeOf<number | null>();
44
+ expectTypeOf<UserState["extra"]>().toEqualTypeOf<ExtractAdapterExtraType<
45
+ ExtractAdapterType<UserRequest>
46
+ > | null>();
47
+ });
48
+ it("should not allow to read unknown fields", () => {
49
+ expectTypeOf<UserState>().not.toHaveProperty("isLoading");
50
+ expectTypeOf<UserState>().not.toHaveProperty("submit");
51
+ expectTypeOf<UserState>().not.toHaveProperty("invalidate");
52
+ });
53
+ });
54
+
55
+ describe("actions", () => {
56
+ it("should type the functions without arguments", () => {
57
+ expectTypeOf<UserState["refetch"]>().toEqualTypeOf<() => void>();
58
+ expectTypeOf<UserState["abort"]>().toEqualTypeOf<() => void>();
59
+ expectTypeOf<UserState["clearState"]>().toEqualTypeOf<() => void>();
60
+ });
61
+ it("should type setData with the response, null and the updater", () => {
62
+ expectTypeOf<UserState["setData"]>().toBeCallableWith({ id: 1, name: "name", tags: [] });
63
+ expectTypeOf<UserState["setData"]>().toBeCallableWith(null);
64
+ expectTypeOf<UserState["setData"]>().toBeCallableWith((previous: User | null) => previous);
65
+ expectTypeOf<UserState["setData"]>().parameter(0).not.toEqualTypeOf<string>();
66
+ });
67
+ it("should type setError with the request error", () => {
68
+ expectTypeOf<UserState["setError"]>().toBeCallableWith({ code: "E", message: "m" });
69
+ expectTypeOf<UserState["setError"]>().toBeCallableWith(new Error("error"));
70
+ expectTypeOf<UserState["setError"]>().toBeCallableWith(null);
71
+ });
72
+ it("should type the bounce state", () => {
73
+ expectTypeOf<UserState["bounce"]>().toEqualTypeOf<{ active: boolean; reset: () => void }>();
74
+ });
75
+ });
76
+
77
+ describe("callbacks", () => {
78
+ it("should pass the success response to onSuccess", () => {
79
+ type Params = Parameters<Parameters<UserState["onSuccess"]>[0]>[0];
80
+
81
+ expectTypeOf<Params["response"]["data"]>().toEqualTypeOf<User>();
82
+ expectTypeOf<Params["response"]["error"]>().toEqualTypeOf<null>();
83
+ expectTypeOf<Params["response"]["success"]>().toEqualTypeOf<true>();
84
+ expectTypeOf<Params["requestId"]>().toEqualTypeOf<string>();
85
+ });
86
+ it("should pass the error response to onError", () => {
87
+ type Params = Parameters<Parameters<UserState["onError"]>[0]>[0];
88
+
89
+ expectTypeOf<Params["response"]["data"]>().toEqualTypeOf<null>();
90
+ expectTypeOf<Params["response"]["error"]>().toEqualTypeOf<ApiError | Error>();
91
+ expectTypeOf<Params["response"]["success"]>().toEqualTypeOf<false>();
92
+ });
93
+ it("should pass any response to onFinished", () => {
94
+ type Params = Parameters<Parameters<UserState["onFinished"]>[0]>[0];
95
+
96
+ expectTypeOf<Params["response"]["data"]>().toEqualTypeOf<User | null>();
97
+ expectTypeOf<Params["response"]["error"]>().toEqualTypeOf<ApiError | Error | null>();
98
+ expectTypeOf<Params["details"]["retries"]>().toEqualTypeOf<number>();
99
+ expectTypeOf<Params["details"]["willRetry"]>().toEqualTypeOf<boolean>();
100
+ });
101
+ });
102
+
103
+ describe("select", () => {
104
+ it("should type data with the selector result", () => {
105
+ const useName = () => useFetch(getUser.setParams({ userId: 1 }), { select: (user) => user.name });
106
+ const useTags = () => useFetch(getUser.setParams({ userId: 1 }), { select: (user) => user.tags.length });
107
+
108
+ expectTypeOf<ReturnType<typeof useName>["data"]>().toEqualTypeOf<string | null>();
109
+ expectTypeOf<ReturnType<typeof useTags>["data"]>().toEqualTypeOf<number | null>();
110
+ });
111
+ it("should type setData with the selected data", () => {
112
+ const useName = () => useFetch(getUser.setParams({ userId: 1 }), { select: (user) => user.name });
113
+
114
+ expectTypeOf<ReturnType<typeof useName>["setData"]>().toBeCallableWith("name");
115
+ expectTypeOf<ReturnType<typeof useName>["setData"]>().parameter(0).not.toEqualTypeOf<User | null>();
116
+ });
117
+ it("should keep the full response in the callbacks", () => {
118
+ const useName = () => useFetch(getUser.setParams({ userId: 1 }), { select: (user) => user.name });
119
+ type Params = Parameters<Parameters<ReturnType<typeof useName>["onSuccess"]>[0]>[0];
120
+
121
+ expectTypeOf<Params["response"]["data"]>().toEqualTypeOf<User>();
122
+ });
123
+ it("should pass the response to the selector", () => {
124
+ type Select = NonNullable<UseFetchOptionsType<UserRequest, string>["select"]>;
125
+
126
+ expectTypeOf<Parameters<Select>[0]>().toEqualTypeOf<User>();
127
+ expectTypeOf<ReturnType<Select>>().toEqualTypeOf<string>();
128
+ });
129
+ });
130
+
131
+ describe("options", () => {
132
+ it("should type the initial response with the request types", () => {
133
+ type InitialResponse = NonNullable<UseFetchOptionsType<UserRequest>["initialResponse"]>;
134
+
135
+ expectTypeOf<InitialResponse["data"]>().toEqualTypeOf<User | null | undefined>();
136
+ expectTypeOf<InitialResponse["error"]>().toEqualTypeOf<ApiError | Error | null | undefined>();
137
+ });
138
+ it("should type the modes and flags", () => {
139
+ type Options = UseFetchOptionsType<UserRequest>;
140
+
141
+ expectTypeOf<Options["keepPreviousData"]>().toEqualTypeOf<"auto" | "preserve" | "clean" | undefined>();
142
+ expectTypeOf<Options["disabled"]>().toEqualTypeOf<boolean | undefined>();
143
+ expectTypeOf<Options["suspense"]>().toEqualTypeOf<boolean | undefined>();
144
+ expectTypeOf<Options["refreshTime"]>().toEqualTypeOf<number | undefined>();
145
+ expectTypeOf<Options["bounceType"]>().toEqualTypeOf<"debounce" | "throttle" | undefined>();
146
+ });
147
+ it("should allow the bounce timeout only in the throttle mode", () => {
148
+ expectTypeOf<{ bounceType: "throttle"; bounceTimeout: number }>().toExtend<UseFetchOptionsType<UserRequest>>();
149
+ expectTypeOf<{ bounceType: "debounce"; bounceTimeout: number }>().not.toExtend<
150
+ UseFetchOptionsType<UserRequest>
151
+ >();
152
+ });
153
+ it("should type the throwOnError predicate with the request error", () => {
154
+ type ThrowOnError = Exclude<UseFetchOptionsType<UserRequest>["throwOnError"], boolean | undefined>;
155
+
156
+ expectTypeOf<Parameters<ThrowOnError>[0]>().toEqualTypeOf<ApiError | Error>();
157
+ });
158
+ });
159
+
160
+ describe("request", () => {
161
+ it("should accept the request with the params set", () => {
162
+ const useUser = () => useFetch(getUser.setParams({ userId: 1 }));
163
+
164
+ expectTypeOf<ReturnType<typeof useUser>["data"]>().toEqualTypeOf<User | null>();
165
+ });
166
+ it("should require the declared params", () => {
167
+ const withParams = () => getUser.setParams({ userId: 1 });
168
+ // @ts-expect-error - params of the endpoint have to be used
169
+ const withWrongParams = () => getUser.setParams({ id: 1 });
170
+
171
+ expectTypeOf(withParams).returns.toHaveProperty("params");
172
+ expectTypeOf(withWrongParams).toBeFunction();
173
+ });
174
+ it("should require the declared query params", () => {
175
+ expectTypeOf(getUsers.setQueryParams).parameter(0).toEqualTypeOf<{ page: number }>();
176
+ });
177
+ it("should share the state types with useCache", () => {
178
+ expectTypeOf<UseCacheReturnType<UserRequest>["data"]>().toEqualTypeOf<UserState["data"]>();
179
+ expectTypeOf<UseCacheReturnType<UserRequest>["error"]>().toEqualTypeOf<UserState["error"]>();
180
+ expectTypeOf<UseCacheReturnType<UserRequest>>().not.toHaveProperty("refetch");
181
+ });
182
+ it("should use the client of the request", () => {
183
+ expectTypeOf(getUser.client).toExtend<Client>();
184
+ });
185
+ });
186
+ });
@@ -0,0 +1,333 @@
1
+ import { act, renderHook } from "@testing-library/react";
2
+ import { useCache } from "hooks/use-cache";
3
+ import { useFetch } from "hooks/use-fetch";
4
+
5
+ import { client, createRequest } from "../../utils";
6
+ import { advance, gateRequest, setCacheResponse, settle } from "../../utils/gate.utils";
7
+
8
+ type Data = { owner: string };
9
+
10
+ /**
11
+ * Scoped requests keep their cache, queue and abort keys separated with the `setScope` prefix,
12
+ * while the events are emitted with the plain keys - hooks must handle only the events of their own scope.
13
+ */
14
+ describe("useFetch [ Scope ]", () => {
15
+ let request = createRequest<Data>();
16
+ let calls = gateRequest(request);
17
+
18
+ const callOf = (scope: string | null) => {
19
+ const call = calls.find((item) => item.request.scope === scope);
20
+ if (!call) {
21
+ throw new Error(`Request of scope ${scope} was not sent`);
22
+ }
23
+ return call;
24
+ };
25
+
26
+ const renderScoped = (scope: string | null, options?: { revalidate?: boolean; disabled?: boolean }) => {
27
+ const scoped = scope ? request.setScope(scope) : request;
28
+ return renderHook(() => {
29
+ const { data, loading, error, refetch } = useFetch(scoped, options);
30
+ return { data, loading, error, refetch };
31
+ });
32
+ };
33
+
34
+ beforeEach(() => {
35
+ vi.useFakeTimers();
36
+ client.clear();
37
+ request = createRequest<Data>();
38
+ calls = gateRequest(request);
39
+ });
40
+
41
+ afterEach(() => {
42
+ vi.useRealTimers();
43
+ });
44
+
45
+ describe("when the scoped request is fetched", () => {
46
+ it("should store the response under the scoped key", async () => {
47
+ const { result } = renderScoped("a");
48
+ await advance();
49
+ callOf("a").succeed({ owner: "a" });
50
+ await settle();
51
+
52
+ expect(result.current.data).toStrictEqual({ owner: "a" });
53
+ expect(client.cache.keys()).toStrictEqual([`a__${request.cacheKey}`]);
54
+ });
55
+ it("should be in the loading state during the refetch", async () => {
56
+ const { result } = renderScoped("a");
57
+ await advance();
58
+ callOf("a").succeed({ owner: "a" });
59
+ await settle();
60
+ expect(result.current.loading).toBeFalse();
61
+
62
+ act(() => {
63
+ result.current.refetch();
64
+ });
65
+ await advance();
66
+
67
+ expect(result.current.loading).toBeTrue();
68
+
69
+ calls[1].succeed({ owner: "a2" });
70
+ await settle();
71
+
72
+ expect(result.current.loading).toBeFalse();
73
+ expect(result.current.data).toStrictEqual({ owner: "a2" });
74
+ });
75
+ it("should read the scoped cache on mount", async () => {
76
+ setCacheResponse(request.setScope("a"), { owner: "a" });
77
+
78
+ const { result } = renderScoped("a", { revalidate: false });
79
+ await advance();
80
+
81
+ expect(result.current.data).toStrictEqual({ owner: "a" });
82
+ expect(calls).toHaveLength(0);
83
+ });
84
+ it("should join the running request of the same scope", async () => {
85
+ act(() => {
86
+ client.fetchDispatcher.add(request.setScope("a"));
87
+ });
88
+ await advance();
89
+
90
+ renderScoped("a");
91
+ await advance();
92
+
93
+ expect(calls).toHaveLength(1);
94
+ });
95
+ });
96
+
97
+ describe("when the same request is used in different scopes", () => {
98
+ it("should send a request for every scope", async () => {
99
+ renderScoped("a");
100
+ renderScoped("b");
101
+ renderScoped(null);
102
+ await advance();
103
+
104
+ expect(calls.map((call) => call.request.scope).toSorted()).toStrictEqual(["a", "b", null].toSorted());
105
+ });
106
+ it("should not show the data of another scope", async () => {
107
+ const scopeA = renderScoped("a");
108
+ const scopeB = renderScoped("b");
109
+ const unscoped = renderScoped(null);
110
+ await advance();
111
+
112
+ callOf("a").succeed({ owner: "a" });
113
+ await settle();
114
+
115
+ expect(scopeA.result.current.data).toStrictEqual({ owner: "a" });
116
+ expect(scopeB.result.current.data).toBeNull();
117
+ expect(unscoped.result.current.data).toBeNull();
118
+ expect(scopeB.result.current.loading).toBeTrue();
119
+ expect(unscoped.result.current.loading).toBeTrue();
120
+ });
121
+ it("should not show the error of another scope", async () => {
122
+ const scopeA = renderScoped("a");
123
+ const scopeB = renderScoped("b");
124
+ await advance();
125
+
126
+ callOf("a").fail(new Error("Scope a failed"));
127
+ await settle();
128
+
129
+ expect(scopeA.result.current.error?.message).toBe("Scope a failed");
130
+ expect(scopeB.result.current.error).toBeNull();
131
+ });
132
+ it("should not show the unscoped data in the scoped hook", async () => {
133
+ const scopeA = renderScoped("a");
134
+ const unscoped = renderScoped(null);
135
+ await advance();
136
+
137
+ callOf(null).succeed({ owner: "nobody" });
138
+ await settle();
139
+
140
+ expect(unscoped.result.current.data).toStrictEqual({ owner: "nobody" });
141
+ expect(scopeA.result.current.data).toBeNull();
142
+ });
143
+ it("should keep the scopes separated in useCache", async () => {
144
+ const cacheB = renderHook(() => useCache(request.setScope("b")).data);
145
+ renderScoped("a");
146
+ await advance();
147
+
148
+ callOf("a").succeed({ owner: "a" });
149
+ await settle();
150
+
151
+ expect(cacheB.result.current).toBeNull();
152
+ });
153
+ it("should not change the loading state of another scope", async () => {
154
+ const scopeA = renderScoped("a", { disabled: true });
155
+ renderScoped("b");
156
+ await advance();
157
+
158
+ expect(scopeA.result.current.loading).toBeFalse();
159
+ });
160
+ it("should call the callbacks of the matching scope only", async () => {
161
+ const onSuccessA = vi.fn();
162
+ const onSuccessB = vi.fn();
163
+ renderHook(() => {
164
+ useFetch(request.setScope("a")).onSuccess(onSuccessA);
165
+ useFetch(request.setScope("b")).onSuccess(onSuccessB);
166
+ });
167
+ await advance();
168
+
169
+ callOf("a").succeed({ owner: "a" });
170
+ await settle();
171
+
172
+ expect(onSuccessA).toHaveBeenCalledOnce();
173
+ expect(onSuccessB).not.toHaveBeenCalled();
174
+ });
175
+ });
176
+
177
+ describe("when the scoped cache changes", () => {
178
+ it("should refetch after invalidation by the request", async () => {
179
+ renderScoped("a");
180
+ await advance();
181
+ callOf("a").succeed({ owner: "a" });
182
+ await settle();
183
+
184
+ act(() => {
185
+ client.cache.invalidate(request.setScope("a"));
186
+ });
187
+ await advance();
188
+
189
+ expect(calls).toHaveLength(2);
190
+ });
191
+ it("should refetch after invalidation by RegExp", async () => {
192
+ renderScoped("a");
193
+ await advance();
194
+ callOf("a").succeed({ owner: "a" });
195
+ await settle();
196
+
197
+ act(() => {
198
+ client.cache.invalidate(/shared-endpoint/);
199
+ });
200
+ await advance();
201
+
202
+ expect(calls).toHaveLength(2);
203
+ });
204
+ it("should refetch after invalidation of the whole cache", async () => {
205
+ renderScoped("a");
206
+ await advance();
207
+ callOf("a").succeed({ owner: "a" });
208
+ await settle();
209
+
210
+ act(() => {
211
+ client.cache.invalidate();
212
+ });
213
+ await advance();
214
+
215
+ expect(calls).toHaveLength(2);
216
+ });
217
+ it("should not refetch when the request of another scope is invalidated", async () => {
218
+ renderScoped("a");
219
+ await advance();
220
+ callOf("a").succeed({ owner: "a" });
221
+ await settle();
222
+ setCacheResponse(request.setScope("b"), { owner: "b" });
223
+
224
+ act(() => {
225
+ client.cache.invalidate(request.setScope("b"));
226
+ client.cache.invalidate(`b__${request.cacheKey}`);
227
+ });
228
+ await advance();
229
+
230
+ expect(calls).toHaveLength(1);
231
+ });
232
+ it("should not refetch when the unscoped request is invalidated", async () => {
233
+ renderScoped("a");
234
+ await advance();
235
+ callOf("a").succeed({ owner: "a" });
236
+ await settle();
237
+
238
+ act(() => {
239
+ client.cache.invalidate(request);
240
+ });
241
+ await advance();
242
+
243
+ expect(calls).toHaveLength(1);
244
+ });
245
+ it("should not refetch when the entry of another scope is deleted", async () => {
246
+ renderScoped("a");
247
+ await advance();
248
+ callOf("a").succeed({ owner: "a" });
249
+ await settle();
250
+ setCacheResponse(request.setScope("b"), { owner: "b" });
251
+
252
+ act(() => {
253
+ client.cache.delete(`b__${request.cacheKey}`);
254
+ });
255
+ await advance();
256
+
257
+ expect(calls).toHaveLength(1);
258
+ });
259
+ it("should refetch every scope once when the whole cache is invalidated", async () => {
260
+ renderScoped("a");
261
+ renderScoped("b");
262
+ await advance();
263
+ callOf("a").succeed({ owner: "a" });
264
+ callOf("b").succeed({ owner: "b" });
265
+ await settle();
266
+
267
+ act(() => {
268
+ client.cache.invalidate();
269
+ });
270
+ await advance();
271
+
272
+ expect(calls.map((call) => call.request.scope)).toStrictEqual(["a", "b", "a", "b"]);
273
+ });
274
+ it("should refetch after the scoped entry is deleted", async () => {
275
+ renderScoped("a");
276
+ await advance();
277
+ callOf("a").succeed({ owner: "a" });
278
+ await settle();
279
+
280
+ act(() => {
281
+ client.cache.delete(`a__${request.cacheKey}`);
282
+ });
283
+ await advance();
284
+
285
+ expect(calls).toHaveLength(2);
286
+ });
287
+ it("should follow the updates of the scoped cache", async () => {
288
+ const { result } = renderScoped("a");
289
+ await advance();
290
+ callOf("a").succeed({ owner: "a" });
291
+ await settle();
292
+
293
+ act(() => {
294
+ setCacheResponse(request.setScope("a"), { owner: "updated" });
295
+ });
296
+
297
+ expect(result.current.data).toStrictEqual({ owner: "updated" });
298
+ });
299
+ });
300
+
301
+ describe("when the scope changes", () => {
302
+ it("should switch to the data of the new scope", async () => {
303
+ setCacheResponse(request.setScope("a"), { owner: "a" });
304
+ setCacheResponse(request.setScope("b"), { owner: "b" });
305
+ const { result, rerender } = renderHook(
306
+ ({ scope }) => {
307
+ const { data } = useFetch(request.setScope(scope), { revalidate: false });
308
+ return { data };
309
+ },
310
+ { initialProps: { scope: "a" } },
311
+ );
312
+ expect(result.current.data).toStrictEqual({ owner: "a" });
313
+
314
+ rerender({ scope: "b" });
315
+
316
+ expect(result.current.data).toStrictEqual({ owner: "b" });
317
+ });
318
+ it("should not keep the data of the previous scope", async () => {
319
+ setCacheResponse(request.setScope("a"), { owner: "a" });
320
+ const { result, rerender } = renderHook(
321
+ ({ scope }) => {
322
+ const { data } = useFetch(request.setScope(scope), { revalidate: false });
323
+ return { data };
324
+ },
325
+ { initialProps: { scope: "a" } },
326
+ );
327
+
328
+ rerender({ scope: "b" });
329
+
330
+ expect(result.current.data).toBeNull();
331
+ });
332
+ });
333
+ });