@hyper-fetch/react 9.6.2 → 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.
@@ -0,0 +1,455 @@
1
+ import type { RequestInstance } from "@hyper-fetch/core";
2
+ import { Client, optimistic } from "@hyper-fetch/core";
3
+ import { act, renderHook, waitFor } from "@testing-library/react";
4
+ import { useFetch } from "hooks/use-fetch";
5
+ import { useInfiniteFetch } from "hooks/use-infinite-fetch";
6
+ import { useSubmit } from "hooks/use-submit";
7
+ import type { ReactNode } from "react";
8
+ import React, { StrictMode } from "react";
9
+
10
+ type Todo = { id: number; done: boolean; likes: number };
11
+
12
+ type Call = {
13
+ request: RequestInstance;
14
+ requestId: string;
15
+ respond: (response: { data?: unknown; error?: unknown }) => void;
16
+ };
17
+
18
+ const todo = (id: number, extra: Partial<Todo> = {}): Todo => ({ id, done: false, likes: 0, ...extra });
19
+ const SERVER = [todo(1), todo(2)];
20
+
21
+ /**
22
+ * Requests wait until the test answers them, only the network part of the adapter is replaced
23
+ */
24
+ const createSetup = () => {
25
+ const client = new Client({ url: "http://localhost:3000" });
26
+ const calls: Call[] = [];
27
+
28
+ client.adapter.setFetcher(({ request, requestId, onSuccess, onError, createAbortListener }) => {
29
+ let isFinished = false;
30
+ const extra = client.adapter.defaultExtra;
31
+ createAbortListener({ status: 0, extra, onAbort: () => (isFinished = true) });
32
+ calls.push({
33
+ request,
34
+ requestId,
35
+ respond: ({ data = null, error }) => {
36
+ if (isFinished) {
37
+ return;
38
+ }
39
+ isFinished = true;
40
+ if (error) {
41
+ onError({ error, status: 500, extra });
42
+ } else {
43
+ onSuccess({ data, status: 200, extra });
44
+ }
45
+ },
46
+ });
47
+ });
48
+
49
+ const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
50
+ const toggle = client
51
+ .createRequest<{ response: Todo; payload: { done: boolean } }>()({ endpoint: "/todos/:todoId", method: "PATCH" })
52
+ .setOptimistic(({ params, payload }) => [
53
+ optimistic(getTodos)
54
+ .patch(params.todoId, payload)
55
+ .rollback(({ data, previous }) => {
56
+ const before = previous.find((item) => item.id === Number(params.todoId));
57
+ return data.map((item) => (item.id === Number(params.todoId) && before ? before : item));
58
+ }),
59
+ ]);
60
+
61
+ const callsTo = (endpoint: string) => calls.filter((call) => call.request.endpoint === endpoint);
62
+ const lastCallTo = async (endpoint: string, count: number) => {
63
+ await waitFor(() => expect(callsTo(endpoint)).toHaveLength(count), { interval: 1 });
64
+ return callsTo(endpoint)[count - 1];
65
+ };
66
+ const answered = new Set<Call>();
67
+ const answer = async (call: Call, response: { data?: unknown; error?: unknown }) => {
68
+ answered.add(call);
69
+ await act(async () => {
70
+ call.respond(response);
71
+ });
72
+ };
73
+ /** Waits for the oldest call to the endpoint which is not answered yet */
74
+ const nextCallTo = async (endpoint: string) => {
75
+ await waitFor(() => expect(callsTo(endpoint).some((call) => !answered.has(call))).toBeTrue(), { interval: 1 });
76
+ return callsTo(endpoint).find((call) => !answered.has(call)) as Call;
77
+ };
78
+ const read = () => client.cache.get<Todo[], unknown>(getTodos.cacheKey)?.data;
79
+
80
+ return { client, calls, getTodos, toggle, callsTo, lastCallTo, nextCallTo, answer, read };
81
+ };
82
+
83
+ type Setup = ReturnType<typeof createSetup>;
84
+
85
+ /** A list and a toggle button in one component, with a log of the rendered list */
86
+ const renderTodos = (setup: Setup, options: { wrapper?: (props: { children: ReactNode }) => ReactNode } = {}) => {
87
+ const renders: (Todo[] | null)[] = [];
88
+ const rendered = renderHook(
89
+ () => {
90
+ const list = useFetch(setup.getTodos, { dependencyTracking: false });
91
+ const button = useSubmit(setup.toggle, { dependencyTracking: false });
92
+ renders.push(list.data);
93
+ return { list, button };
94
+ },
95
+ { wrapper: options.wrapper },
96
+ );
97
+ return { ...rendered, renders };
98
+ };
99
+
100
+ const loadList = async (setup: Setup, data: Todo[] = SERVER) => {
101
+ await setup.answer(await setup.nextCallTo("/todos"), { data });
102
+ };
103
+
104
+ const doneOf = (list: Todo[] | null | undefined, id: number) => list?.find((item) => item.id === id)?.done;
105
+
106
+ describe("useSubmit [ Optimistic helpers ]", () => {
107
+ describe("when submitting", () => {
108
+ it("should show the change before the response and keep it without flicker on success", async () => {
109
+ const setup = createSetup();
110
+ const { result, renders } = renderTodos(setup);
111
+ await loadList(setup);
112
+
113
+ act(() => {
114
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
115
+ });
116
+ expect(doneOf(result.current.list.data, 1)).toBeTrue();
117
+
118
+ const mutation = await setup.lastCallTo("/todos/1", 1);
119
+ await setup.answer(mutation, { data: todo(1, { done: true }) });
120
+
121
+ // The refresh after the mutation reads the confirmed data
122
+ await loadList(setup, [todo(1, { done: true }), todo(2)]);
123
+ expect(doneOf(result.current.list.data, 1)).toBeTrue();
124
+
125
+ const firstOptimistic = renders.findIndex((list) => doneOf(list, 1) === true);
126
+ expect(renders.slice(firstOptimistic).every((list) => doneOf(list, 1) === true)).toBeTrue();
127
+ });
128
+
129
+ it("should revert on error and show the server data after the refresh", async () => {
130
+ const setup = createSetup();
131
+ const { result } = renderTodos(setup);
132
+ await loadList(setup);
133
+
134
+ act(() => {
135
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
136
+ });
137
+ const mutation = await setup.lastCallTo("/todos/1", 1);
138
+ await setup.answer(mutation, { error: new Error("Failed") });
139
+
140
+ expect(doneOf(result.current.list.data, 1)).toBeFalse();
141
+ await loadList(setup, [todo(1, { likes: 3 }), todo(2)]);
142
+ expect(result.current.list.data).toStrictEqual([todo(1, { likes: 3 }), todo(2)]);
143
+ });
144
+
145
+ it("should settle a mutation of an unmounted component", async () => {
146
+ const setup = createSetup();
147
+ const { result, unmount } = renderTodos(setup);
148
+ await loadList(setup);
149
+
150
+ act(() => {
151
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
152
+ });
153
+ const mutation = await setup.lastCallTo("/todos/1", 1);
154
+ unmount();
155
+ await setup.answer(mutation, { error: new Error("Failed") });
156
+
157
+ expect(doneOf(setup.read(), 1)).toBeFalse();
158
+
159
+ // A remount shows the reverted value
160
+ const remounted = renderTodos(setup);
161
+ expect(doneOf(remounted.result.current.list.data, 1)).toBeFalse();
162
+ });
163
+
164
+ it("should update every component reading the key", async () => {
165
+ const setup = createSetup();
166
+ const first = renderTodos(setup);
167
+ await loadList(setup);
168
+ const second = renderHook(() => useFetch(setup.getTodos, { dependencyTracking: false }));
169
+
170
+ act(() => {
171
+ first.result.current.button.submit({ params: { todoId: 2 }, payload: { done: true } });
172
+ });
173
+
174
+ expect(doneOf(first.result.current.list.data, 2)).toBeTrue();
175
+ expect(doneOf(second.result.current.data, 2)).toBeTrue();
176
+ });
177
+
178
+ it("should apply the change once in StrictMode", async () => {
179
+ const setup = createSetup();
180
+ const like = setup.client
181
+ .createRequest<{ response: null }>()({ endpoint: "/like", method: "POST" })
182
+ .setOptimistic(() => [optimistic(setup.getTodos).increment(1, "likes", 1)]);
183
+ const wrapper = ({ children }: { children: ReactNode }) => <StrictMode>{children}</StrictMode>;
184
+ const { result } = renderHook(
185
+ () => ({
186
+ list: useFetch(setup.getTodos, { dependencyTracking: false }),
187
+ button: useSubmit(like, { dependencyTracking: false }),
188
+ }),
189
+ { wrapper },
190
+ );
191
+ await waitFor(() => expect(setup.callsTo("/todos").length).toBeGreaterThan(0), { interval: 1 });
192
+ await Promise.all(setup.callsTo("/todos").map((call) => setup.answer(call, { data: SERVER })));
193
+
194
+ act(() => {
195
+ result.current.button.submit();
196
+ });
197
+
198
+ expect(result.current.list.data?.[0].likes).toBe(1);
199
+ });
200
+ });
201
+
202
+ describe("when toggling rapidly", () => {
203
+ it("should end on the server value after ten clicks with mixed outcomes", async () => {
204
+ const setup = createSetup();
205
+ const { result } = renderTodos(setup);
206
+ await loadList(setup);
207
+ let server = [...SERVER];
208
+ const outcomes = [true, false, true, true, false, false, true, false, true, false];
209
+
210
+ for (const [index] of outcomes.entries()) {
211
+ act(() => {
212
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: index % 2 === 0 } });
213
+ });
214
+ }
215
+ expect(doneOf(result.current.list.data, 1)).toBeFalse();
216
+
217
+ const mutations = await setup.lastCallTo("/todos/1", outcomes.length).then(() => setup.callsTo("/todos/1"));
218
+ // The server answers in reverse order
219
+ for (const index of [...outcomes.keys()].toReversed()) {
220
+ if (outcomes[index]) {
221
+ server = server.map((item) => (item.id === 1 ? { ...item, done: index % 2 === 0 } : item));
222
+ // eslint-disable-next-line no-await-in-loop
223
+ await setup.answer(mutations[index], { data: server[0] });
224
+ } else {
225
+ // eslint-disable-next-line no-await-in-loop
226
+ await setup.answer(mutations[index], { error: new Error("Failed") });
227
+ }
228
+ }
229
+
230
+ // One refresh after the last mutation
231
+ await loadList(setup, server);
232
+ expect(result.current.list.data).toStrictEqual(server);
233
+ expect(setup.callsTo("/todos")).toHaveLength(2);
234
+ });
235
+ });
236
+
237
+ describe("when the list is fetched during a pending change", () => {
238
+ it("should discard a manual refetch that started before the change settled", async () => {
239
+ const setup = createSetup();
240
+ const { result } = renderTodos(setup);
241
+ await loadList(setup);
242
+
243
+ act(() => {
244
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
245
+ });
246
+ act(() => {
247
+ result.current.list.refetch();
248
+ });
249
+ const refetch = await setup.lastCallTo("/todos", 2);
250
+ await setup.answer(refetch, { data: SERVER });
251
+
252
+ expect(doneOf(result.current.list.data, 1)).toBeTrue();
253
+
254
+ const mutation = await setup.lastCallTo("/todos/1", 1);
255
+ await setup.answer(mutation, { data: todo(1, { done: true }) });
256
+ await loadList(setup, [todo(1, { done: true }), todo(2)]);
257
+ expect(doneOf(result.current.list.data, 1)).toBeTrue();
258
+ });
259
+
260
+ it("should discard a refetch on focus that started before the change settled", async () => {
261
+ const setup = createSetup();
262
+ const renders: (Todo[] | null)[] = [];
263
+ const { result } = renderHook(() => {
264
+ const list = useFetch(setup.getTodos, { dependencyTracking: false, refetchOnFocus: true });
265
+ const button = useSubmit(setup.toggle, { dependencyTracking: false });
266
+ renders.push(list.data);
267
+ return { list, button };
268
+ });
269
+ await loadList(setup);
270
+
271
+ act(() => {
272
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
273
+ });
274
+ act(() => {
275
+ setup.client.appManager.setFocused(false);
276
+ setup.client.appManager.setFocused(true);
277
+ });
278
+ const focusFetch = await setup.lastCallTo("/todos", 2);
279
+ const mutation = await setup.lastCallTo("/todos/1", 1);
280
+ await setup.answer(mutation, { data: todo(1, { done: true }) });
281
+ await setup.answer(focusFetch, { data: SERVER });
282
+
283
+ expect(doneOf(result.current.list.data, 1)).toBeTrue();
284
+ await loadList(setup, [todo(1, { done: true }), todo(2)]);
285
+ expect(doneOf(result.current.list.data, 1)).toBeTrue();
286
+ });
287
+
288
+ it("should discard a polling refresh while the change is pending", async () => {
289
+ const setup = createSetup();
290
+ const { result } = renderHook(() => ({
291
+ list: useFetch(setup.getTodos, { dependencyTracking: false, refresh: true, refreshTime: 20 }),
292
+ button: useSubmit(setup.toggle, { dependencyTracking: false }),
293
+ }));
294
+ await loadList(setup);
295
+
296
+ act(() => {
297
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
298
+ });
299
+ const poll = await setup.lastCallTo("/todos", 2);
300
+ await setup.answer(poll, { data: SERVER });
301
+
302
+ expect(doneOf(result.current.list.data, 1)).toBeTrue();
303
+ const mutation = await setup.lastCallTo("/todos/1", 1);
304
+ await setup.answer(mutation, { error: new Error("Failed") });
305
+ expect(doneOf(result.current.list.data, 1)).toBeFalse();
306
+ });
307
+ });
308
+
309
+ describe("when passing optimistic to the hook", () => {
310
+ it("should use the hook option and let submit() override it", async () => {
311
+ const setup = createSetup();
312
+ const plain = setup.client.createRequest<{ response: null }>()({ endpoint: "/plain", method: "POST" });
313
+ const { result } = renderHook(() => ({
314
+ list: useFetch(setup.getTodos, { dependencyTracking: false }),
315
+ button: useSubmit(plain, {
316
+ dependencyTracking: false,
317
+ optimistic: [optimistic(setup.getTodos).patch(1, { likes: 1 })],
318
+ }),
319
+ }));
320
+ await loadList(setup);
321
+
322
+ act(() => {
323
+ result.current.button.submit();
324
+ });
325
+ expect(result.current.list.data?.[0].likes).toBe(1);
326
+
327
+ act(() => {
328
+ result.current.button.submit({ optimistic: [optimistic(setup.getTodos).patch(2, { likes: 5 })] });
329
+ });
330
+ expect(result.current.list.data?.map((item) => item.likes)).toStrictEqual([1, 5]);
331
+ });
332
+
333
+ it("should replace the request's callback with the hook option", async () => {
334
+ const setup = createSetup();
335
+ const { result } = renderHook(() => ({
336
+ list: useFetch(setup.getTodos, { dependencyTracking: false }),
337
+ button: useSubmit(setup.toggle, {
338
+ dependencyTracking: false,
339
+ optimistic: ({ params }) => [optimistic(setup.getTodos).remove(params.todoId)],
340
+ }),
341
+ }));
342
+ await loadList(setup);
343
+
344
+ act(() => {
345
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
346
+ });
347
+
348
+ expect(result.current.list.data).toStrictEqual([todo(2)]);
349
+ });
350
+ });
351
+
352
+ describe("when settling through useSubmit", () => {
353
+ it.each([
354
+ { name: "success", response: { data: todo(1, { done: true }) }, done: true, reverted: false },
355
+ { name: "final error", response: { error: new Error("Failed") }, done: false, reverted: true },
356
+ ])("should settle $name", async ({ response, done }) => {
357
+ const setup = createSetup();
358
+ const { result } = renderTodos(setup);
359
+ await loadList(setup);
360
+ const onSettled = vi.fn();
361
+
362
+ act(() => {
363
+ result.current.button.onSubmitFinished(onSettled);
364
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
365
+ });
366
+ const mutation = await setup.lastCallTo("/todos/1", 1);
367
+ await setup.answer(mutation, response);
368
+
369
+ expect(doneOf(result.current.list.data, 1)).toBe(done);
370
+ expect(onSettled).toHaveBeenCalledTimes(1);
371
+ // The list is refetched once
372
+ await setup.lastCallTo("/todos", 2);
373
+ });
374
+
375
+ it("should settle abort", async () => {
376
+ const setup = createSetup();
377
+ const { result } = renderTodos(setup);
378
+ await loadList(setup);
379
+
380
+ act(() => {
381
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
382
+ });
383
+ await setup.lastCallTo("/todos/1", 1);
384
+ await act(async () => {
385
+ result.current.button.abort();
386
+ });
387
+
388
+ expect(doneOf(result.current.list.data, 1)).toBeFalse();
389
+ });
390
+
391
+ it("should keep the change while retrying", async () => {
392
+ const setup = createSetup();
393
+ const retried = setup.toggle.setRetry(1).setRetryTime(0);
394
+ const { result } = renderHook(() => ({
395
+ list: useFetch(setup.getTodos, { dependencyTracking: false }),
396
+ button: useSubmit(retried, { dependencyTracking: false }),
397
+ }));
398
+ await loadList(setup);
399
+
400
+ act(() => {
401
+ result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
402
+ });
403
+ await setup.answer(await setup.lastCallTo("/todos/1", 1), { error: new Error("Failed") });
404
+ expect(doneOf(result.current.list.data, 1)).toBeTrue();
405
+
406
+ await setup.answer(await setup.lastCallTo("/todos/1", 2), { error: new Error("Failed") });
407
+ expect(doneOf(result.current.list.data, 1)).toBeFalse();
408
+ });
409
+ });
410
+
411
+ describe("when the list is infinite", () => {
412
+ it("should change and revert every loaded page with optimistic.all", async () => {
413
+ const setup = createSetup();
414
+ const getPages = setup.client.createRequest<{ response: Todo[]; queryParams: { page?: number } }>()({
415
+ endpoint: "/pages",
416
+ });
417
+ const remove = setup.client
418
+ .createRequest<{ response: null }>()({ endpoint: "/pages/:id", method: "DELETE" })
419
+ .setOptimistic(({ params }) => [
420
+ optimistic
421
+ .all(getPages)
422
+ .remove(params.id)
423
+ .rollback(({ data, previous }) => {
424
+ const index = previous.findIndex((item) => item.id === Number(params.id));
425
+ if (index === -1) {
426
+ return data;
427
+ }
428
+ const next = [...data];
429
+ next.splice(index, 0, previous[index]);
430
+ return next;
431
+ }),
432
+ ]);
433
+ const { result } = renderHook(() => ({
434
+ list: useInfiniteFetch(getPages, { pagination: { page: "page" }, dependencyTracking: false }),
435
+ button: useSubmit(remove, { dependencyTracking: false }),
436
+ }));
437
+ await setup.answer(await setup.lastCallTo("/pages", 1), { data: [todo(1), todo(2)] });
438
+ await waitFor(() => expect(result.current.list.items).toHaveLength(2));
439
+ let nextPage: Promise<unknown> = Promise.resolve();
440
+ act(() => {
441
+ nextPage = result.current.list.fetchNextPage();
442
+ });
443
+ await setup.answer(await setup.lastCallTo("/pages", 2), { data: [todo(3), todo(4)] });
444
+ await act(() => nextPage);
445
+
446
+ act(() => {
447
+ result.current.button.submit({ params: { id: 3 } });
448
+ });
449
+ await waitFor(() => expect(result.current.list.items.map((item) => item.id)).toStrictEqual([1, 2, 4]));
450
+
451
+ await setup.answer(await setup.lastCallTo("/pages/3", 1), { error: new Error("Failed") });
452
+ await waitFor(() => expect(result.current.list.items.map((item) => item.id)).toStrictEqual([1, 2, 3, 4]));
453
+ });
454
+ });
455
+ });
@@ -1,6 +1,6 @@
1
1
  import { RequestInstance, RequiredKeys } from '@hyper-fetch/core';
2
2
  import { UseSubmitOptionsType } from './use-submit.types';
3
- type DefaultOptionsType = RequiredKeys<Omit<UseSubmitOptionsType<RequestInstance>, "initialResponse" | "select">> & {
3
+ type DefaultOptionsType = RequiredKeys<Omit<UseSubmitOptionsType<RequestInstance>, "initialResponse" | "select" | "optimistic">> & {
4
4
  initialResponse: null;
5
5
  };
6
6
  export declare const useSubmitDefaultOptions: DefaultOptionsType;
@@ -1 +1 @@
1
- {"version":3,"file":"use-submit.constants.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-submit/use-submit.constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEvE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE/D,KAAK,kBAAkB,GAAG,YAAY,CAAC,IAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,EAAE,iBAAiB,GAAG,QAAQ,CAAC,CAAC,GAAG;IAClH,eAAe,EAAE,IAAI,CAAC;CACvB,CAAC;AAEF,eAAO,MAAM,uBAAuB,EAAE,kBASrC,CAAC"}
1
+ {"version":3,"file":"use-submit.constants.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-submit/use-submit.constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEvE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE/D,KAAK,kBAAkB,GAAG,YAAY,CACpC,IAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,EAAE,iBAAiB,GAAG,QAAQ,GAAG,YAAY,CAAC,CACzF,GAAG;IACF,eAAe,EAAE,IAAI,CAAC;CACvB,CAAC;AAEF,eAAO,MAAM,uBAAuB,EAAE,kBASrC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-submit.hooks.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-submit/use-submit.hooks.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,eAAe,EAEf,mBAAmB,EAKpB,MAAM,mBAAmB,CAAC;AAI3B,OAAO,KAAK,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAMlF;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAI,WAAW,SAAS,eAAe,EAAE,SAAS,GAAG,mBAAmB,CAAC,WAAW,CAAC,EACzG,SAAS,WAAW,EACpB,UAAU,oBAAoB,CAAC,WAAW,EAAE,SAAS,CAAC,KACrD,mBAAmB,CAAC,WAAW,EAAE,SAAS,CAgV5C,CAAC"}
1
+ {"version":3,"file":"use-submit.hooks.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-submit/use-submit.hooks.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,eAAe,EAEf,mBAAmB,EAKpB,MAAM,mBAAmB,CAAC;AAI3B,OAAO,KAAK,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAMlF;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAI,WAAW,SAAS,eAAe,EAAE,SAAS,GAAG,mBAAmB,CAAC,WAAW,CAAC,EACzG,SAAS,WAAW,EACpB,UAAU,oBAAoB,CAAC,WAAW,EAAE,SAAS,CAAC,KACrD,mBAAmB,CAAC,WAAW,EAAE,SAAS,CAoV5C,CAAC"}
@@ -1,4 +1,4 @@
1
- import { ExtractAdapterResolvedType, ExtractResponseType, NullableType, RequestInstance, RequestSendType } from '@hyper-fetch/core';
1
+ import { ExtractAdapterResolvedType, ExtractResponseType, NullableType, OptimisticSendOptionType, RequestInstance, RequestSendType } from '@hyper-fetch/core';
2
2
  import { OnProgressCallbackType, OnStartCallbackType, OnSuccessCallbackType, OnErrorCallbackType, OnFinishedCallbackType, UseTrackedStateType, UseTrackedStateActions, UseTrackedStateSelect } from '../../helpers';
3
3
  import { isEqual } from '../../utils';
4
4
  export type UseSubmitOptionsType<T extends RequestInstance, TSelected = ExtractResponseType<T>> = {
@@ -31,6 +31,11 @@ export type UseSubmitOptionsType<T extends RequestInstance, TSelected = ExtractR
31
31
  * Keep references of the unchanged parts of the selected data between updates (default true).
32
32
  */
33
33
  structuralSharing?: boolean;
34
+ /**
35
+ * Optimistic update of every submit from this hook - `optimistic()` operations or a callback like the one of
36
+ * `setOptimistic`. Replaces the request's own optimistic callback; `submit({ optimistic })` replaces this one.
37
+ */
38
+ optimistic?: OptimisticSendOptionType<T>;
34
39
  } & ({
35
40
  /**
36
41
  * Possibility to choose between debounce and throttle approaches
@@ -1 +1 @@
1
- {"version":3,"file":"use-submit.types.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-submit/use-submit.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,mBAAmB,EACnB,YAAY,EACZ,eAAe,EACf,eAAe,EAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,EACnB,sBAAsB,E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,MAAM,EAAE,OAAO,CAAC;QAChB;;WAEG;QACH,KAAK,EAAE,MAAM,IAAI,CAAC;KACnB,CAAC;IACF;;OAEG;IACH,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB,CAAC"}
package/dist/index.mjs CHANGED
@@ -2703,12 +2703,15 @@ var useSubmit = (request, options) => {
2703
2703
  });
2704
2704
  return Promise.resolve(getNotSentResponse("Cannot submit request. Option 'disabled' is enabled"));
2705
2705
  }
2706
- const requestClone = request.clone(submitOptions);
2706
+ const { optimistic: submitOptimistic, ...cloneOptions } = submitOptions || {};
2707
+ const requestClone = request.clone(cloneOptions);
2708
+ const optimistic = submitOptimistic ?? options?.optimistic;
2707
2709
  const triggerRequest = () => {
2708
2710
  addCacheDataListener(requestClone);
2709
2711
  return sendRequest(requestClone, {
2710
2712
  dispatcherType: "submit",
2711
2713
  ...submitOptions,
2714
+ optimistic,
2712
2715
  onBeforeSent: (data) => {
2713
2716
  removeLifecycleListener(data.requestId);
2714
2717
  addLifecycleListeners(requestClone, data.requestId, data.mutationContext);