@firtoz/router-toolkit 5.3.0 → 5.4.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.
- package/README.md +40 -0
- package/package.json +7 -7
- package/src/index.ts +1 -0
- package/src/useConcurrentDynamicSubmitter.tsx +173 -0
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@ Type-safe React Router 7 framework mode helpers with enhanced fetching, form sub
|
|
|
13
13
|
- ✅ **Type-safe routing** - Full TypeScript support with React Router 7 framework mode
|
|
14
14
|
- 🚀 **Enhanced fetching** - Dynamic fetchers with caching and query parameter support
|
|
15
15
|
- 📝 **Form submission** - Type-safe form handling with Zod validation
|
|
16
|
+
- 📤 **Concurrent submissions** - Multiple parallel submissions per action with per-operation tracking and optimistic UI (`useConcurrentDynamicSubmitter`)
|
|
16
17
|
- 🔄 **State tracking** - Monitor fetcher state changes with ease
|
|
17
18
|
- 🎯 **Zero configuration** - Works out of the box with React Router 7
|
|
18
19
|
- 📦 **Tree-shakeable** - Import only what you need
|
|
@@ -278,6 +279,45 @@ export default function ContactForm() {
|
|
|
278
279
|
}
|
|
279
280
|
```
|
|
280
281
|
|
|
282
|
+
### `useConcurrentDynamicSubmitter`
|
|
283
|
+
|
|
284
|
+
Run multiple submissions to the same action in parallel, each tracked independently. No single fetcher; each call returns `{ id, promise }` and adds an entry to `operations` with `submittedData` (for optimistic UI) and `data` when done.
|
|
285
|
+
|
|
286
|
+
```tsx
|
|
287
|
+
import { useConcurrentDynamicSubmitter } from '@firtoz/router-toolkit';
|
|
288
|
+
|
|
289
|
+
function UploadList() {
|
|
290
|
+
const { operations, submitJson } = useConcurrentDynamicSubmitter<
|
|
291
|
+
typeof import("./api.upload")
|
|
292
|
+
>("/api/upload");
|
|
293
|
+
|
|
294
|
+
const handleUpload = (file: { name: string; size: number }) => {
|
|
295
|
+
submitJson({ fileName: file.name, size: file.size });
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
return (
|
|
299
|
+
<ul>
|
|
300
|
+
{Object.values(operations).map((op) => (
|
|
301
|
+
<li key={op.id}>
|
|
302
|
+
{op.status === "pending" && (
|
|
303
|
+
<Skeleton>{op.submittedData.fileName}</Skeleton>
|
|
304
|
+
)}
|
|
305
|
+
{op.status === "done" && (
|
|
306
|
+
<span>Saved: {op.data?.id}</span>
|
|
307
|
+
)}
|
|
308
|
+
{op.status === "error" && (
|
|
309
|
+
<span>Failed: {String(op.error)}</span>
|
|
310
|
+
)}
|
|
311
|
+
</li>
|
|
312
|
+
))}
|
|
313
|
+
</ul>
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
- **`operations`**: `Record<string, Operation<T>>` — each operation has `id`, `status` (`"pending"` | `"done"` | `"error"`), `submittedData` (payload sent), and when done `data` (action response).
|
|
319
|
+
- **`submitJson(data)`**: returns `{ id, promise }`; use `id` to look up in `operations`, `promise` to await.
|
|
320
|
+
|
|
281
321
|
### `useFetcherStateChanged`
|
|
282
322
|
|
|
283
323
|
Track changes in fetcher state and react to them. Perfect for triggering side effects, showing notifications, or handling state transitions in your application.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@firtoz/router-toolkit",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.4.0",
|
|
4
4
|
"description": "Type-safe React Router 7 framework mode helpers with enhanced fetching, form submission, and state management",
|
|
5
5
|
"main": "./src/index.ts",
|
|
6
6
|
"module": "./src/index.ts",
|
|
@@ -56,9 +56,9 @@
|
|
|
56
56
|
},
|
|
57
57
|
"peerDependencies": {
|
|
58
58
|
"@firtoz/maybe-error": "^1.5.1",
|
|
59
|
-
"react": "^19.2.
|
|
60
|
-
"react-router": "^7.
|
|
61
|
-
"zod": "^4.3.
|
|
59
|
+
"react": "^19.2.4",
|
|
60
|
+
"react-router": "^7.13.0",
|
|
61
|
+
"zod": "^4.3.6"
|
|
62
62
|
},
|
|
63
63
|
"engines": {
|
|
64
64
|
"node": ">=18.0.0"
|
|
@@ -72,8 +72,8 @@
|
|
|
72
72
|
"devDependencies": {
|
|
73
73
|
"@testing-library/react": "^16.3.1",
|
|
74
74
|
"@types/jsdom": "^27.0.0",
|
|
75
|
-
"@types/react": "^19.2.
|
|
76
|
-
"bun-types": "^1.3.
|
|
77
|
-
"jsdom": "^
|
|
75
|
+
"@types/react": "^19.2.14",
|
|
76
|
+
"bun-types": "^1.3.9",
|
|
77
|
+
"jsdom": "^28.1.0"
|
|
78
78
|
}
|
|
79
79
|
}
|
package/src/index.ts
CHANGED
|
@@ -3,5 +3,6 @@ export * from "./types/index";
|
|
|
3
3
|
export * from "./useCachedFetch";
|
|
4
4
|
export * from "./useDynamicFetcher";
|
|
5
5
|
export * from "./useDynamicSubmitter";
|
|
6
|
+
export * from "./useConcurrentDynamicSubmitter";
|
|
6
7
|
export * from "./useFetcherStateChanged";
|
|
7
8
|
// Test comment to trigger release
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Concurrent type-safe form submissions for React Router 7
|
|
3
|
+
*
|
|
4
|
+
* Lets you run multiple submissions to the same (or logical) action in parallel,
|
|
5
|
+
* each tracked independently with pending → done state. No single fetcher;
|
|
6
|
+
* each submission is a promise and an entry in `operations`.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```tsx
|
|
10
|
+
* const { operations, submitJson } = useConcurrentDynamicSubmitter<typeof import("./api.upload")>("/api/upload");
|
|
11
|
+
*
|
|
12
|
+
* const a = submitJson({ fileId: "1", name: "a.pdf" });
|
|
13
|
+
* const b = submitJson({ fileId: "2", name: "b.pdf" });
|
|
14
|
+
*
|
|
15
|
+
* // Map operations: show submittedData optimistically (skeleton/list), then response when done
|
|
16
|
+
* {Object.values(operations).map((op) => (
|
|
17
|
+
* <div key={op.id}>
|
|
18
|
+
* {op.status === "pending" && <Skeleton />}
|
|
19
|
+
* {op.status === "done" && <Item data={op.data} />}
|
|
20
|
+
* <span>{op.submittedData.name}</span>
|
|
21
|
+
* </div>
|
|
22
|
+
* ))}
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { useCallback, useMemo, useRef, useState } from "react";
|
|
27
|
+
import { href } from "react-router";
|
|
28
|
+
import type { z } from "zod";
|
|
29
|
+
import type { HrefArgs } from "./types/HrefArgs";
|
|
30
|
+
import type { RegisterPages } from "./types/RegisterPages";
|
|
31
|
+
|
|
32
|
+
type RouteModule = {
|
|
33
|
+
route: keyof RegisterPages;
|
|
34
|
+
action: (...args: unknown[]) => unknown;
|
|
35
|
+
formSchema: z.ZodType;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Action result type inferred from the route module's action */
|
|
39
|
+
export type ActionResult<TModule extends RouteModule> = Awaited<
|
|
40
|
+
ReturnType<TModule["action"]>
|
|
41
|
+
>;
|
|
42
|
+
|
|
43
|
+
/** Status of a single concurrent submission */
|
|
44
|
+
export type OperationStatus = "pending" | "done" | "error";
|
|
45
|
+
|
|
46
|
+
/** One tracked submission: pending → done (or error). Includes submitted payload for optimistic UI. */
|
|
47
|
+
export type Operation<TResponse, TFormData = unknown> = {
|
|
48
|
+
id: string;
|
|
49
|
+
status: OperationStatus;
|
|
50
|
+
/** Data that was sent (for optimistic display while pending, or to show what was submitted) */
|
|
51
|
+
submittedData: TFormData;
|
|
52
|
+
/** Response from the action when status is "done" */
|
|
53
|
+
data?: TResponse;
|
|
54
|
+
error?: unknown;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** Result of submitJson: id to look up in operations, promise to await */
|
|
58
|
+
export type SubmitJsonResult<T> = {
|
|
59
|
+
id: string;
|
|
60
|
+
promise: Promise<T>;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type SubmitJsonOptions = {
|
|
64
|
+
method?: "POST" | "PUT" | "PATCH" | "DELETE";
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Submits JSON to the action URL via fetch and returns the parsed JSON.
|
|
69
|
+
* Used so we can run N requests in parallel without N fetchers.
|
|
70
|
+
*/
|
|
71
|
+
async function submitJsonToAction<T>(
|
|
72
|
+
actionUrl: string,
|
|
73
|
+
data: unknown,
|
|
74
|
+
options: SubmitJsonOptions & { fetchFn?: typeof fetch },
|
|
75
|
+
): Promise<T> {
|
|
76
|
+
const { method = "POST", fetchFn = fetch } = options;
|
|
77
|
+
const res = await fetchFn(actionUrl, {
|
|
78
|
+
method,
|
|
79
|
+
headers: { "Content-Type": "application/json" },
|
|
80
|
+
body: JSON.stringify(data),
|
|
81
|
+
});
|
|
82
|
+
if (!res.ok) {
|
|
83
|
+
const text = await res.text();
|
|
84
|
+
throw new Error(`Action failed: ${res.status} ${text}`);
|
|
85
|
+
}
|
|
86
|
+
const json = (await res.json()) as T;
|
|
87
|
+
return json;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Hook for multiple concurrent submissions to a dynamic route action.
|
|
92
|
+
* Each submission gets an id and appears in `operations` as pending → done (or error).
|
|
93
|
+
* Strongly typed: form data from route's formSchema, result from action return type.
|
|
94
|
+
*
|
|
95
|
+
* @template TInfo - Route module type (e.g. `typeof import("./api.upload")`)
|
|
96
|
+
* @param path - Route path
|
|
97
|
+
* @param args - Route params if path has segments
|
|
98
|
+
* @returns operations map (id → Operation), submitJson (returns { id, promise })
|
|
99
|
+
*/
|
|
100
|
+
export function useConcurrentDynamicSubmitter<TInfo extends RouteModule>(
|
|
101
|
+
path: TInfo["route"],
|
|
102
|
+
...args: TInfo["route"] extends "undefined"
|
|
103
|
+
? HrefArgs<"/">
|
|
104
|
+
: HrefArgs<TInfo["route"]>
|
|
105
|
+
): {
|
|
106
|
+
operations: Record<
|
|
107
|
+
string,
|
|
108
|
+
Operation<ActionResult<TInfo>, z.infer<TInfo["formSchema"]>>
|
|
109
|
+
>;
|
|
110
|
+
submitJson: (
|
|
111
|
+
data: z.infer<TInfo["formSchema"]>,
|
|
112
|
+
options?: SubmitJsonOptions,
|
|
113
|
+
) => SubmitJsonResult<ActionResult<TInfo>>;
|
|
114
|
+
} {
|
|
115
|
+
const actionUrl = useMemo(() => {
|
|
116
|
+
// biome-ignore lint/suspicious/noExplicitAny: Intentional
|
|
117
|
+
return href(path, ...(args as any));
|
|
118
|
+
}, [path, args]);
|
|
119
|
+
|
|
120
|
+
type FormData = z.infer<TInfo["formSchema"]>;
|
|
121
|
+
type Op = Operation<ActionResult<TInfo>, FormData>;
|
|
122
|
+
|
|
123
|
+
const nextIdRef = useRef(0);
|
|
124
|
+
const [operations, setOperations] = useState<Record<string, Op>>({});
|
|
125
|
+
|
|
126
|
+
const submitJson = useCallback(
|
|
127
|
+
(
|
|
128
|
+
data: FormData,
|
|
129
|
+
options: SubmitJsonOptions = {},
|
|
130
|
+
): SubmitJsonResult<ActionResult<TInfo>> => {
|
|
131
|
+
const id = `op-${++nextIdRef.current}`;
|
|
132
|
+
setOperations((prev) => ({
|
|
133
|
+
...prev,
|
|
134
|
+
[id]: { id, status: "pending", submittedData: data },
|
|
135
|
+
}));
|
|
136
|
+
|
|
137
|
+
const promise = submitJsonToAction<ActionResult<TInfo>>(
|
|
138
|
+
actionUrl,
|
|
139
|
+
data,
|
|
140
|
+
options,
|
|
141
|
+
)
|
|
142
|
+
.then((responseData) => {
|
|
143
|
+
setOperations((prev) => ({
|
|
144
|
+
...prev,
|
|
145
|
+
[id]: {
|
|
146
|
+
id,
|
|
147
|
+
status: "done",
|
|
148
|
+
submittedData: data,
|
|
149
|
+
data: responseData,
|
|
150
|
+
},
|
|
151
|
+
}));
|
|
152
|
+
return responseData;
|
|
153
|
+
})
|
|
154
|
+
.catch((error) => {
|
|
155
|
+
setOperations((prev) => ({
|
|
156
|
+
...prev,
|
|
157
|
+
[id]: {
|
|
158
|
+
id,
|
|
159
|
+
status: "error",
|
|
160
|
+
submittedData: data,
|
|
161
|
+
error,
|
|
162
|
+
},
|
|
163
|
+
}));
|
|
164
|
+
throw error;
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
return { id, promise };
|
|
168
|
+
},
|
|
169
|
+
[actionUrl],
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
return { operations, submitJson };
|
|
173
|
+
}
|