@railway-ts/use-form 0.2.0 → 0.3.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 +8 -8
- package/dist/index.d.mts +66 -20
- package/dist/index.mjs +304 -144
- package/dist/index.mjs.map +1 -1
- package/docs/API.md +70 -33
- package/docs/GETTING_STARTED.md +14 -9
- package/docs/RECIPES.md +70 -69
- package/package.json +7 -6
package/docs/API.md
CHANGED
|
@@ -9,12 +9,16 @@ Main hook for form management.
|
|
|
9
9
|
### Signature
|
|
10
10
|
|
|
11
11
|
```typescript
|
|
12
|
-
function useForm<TValues extends Record<string, unknown
|
|
12
|
+
function useForm<TValues extends Record<string, unknown>, TResult = TValues>(
|
|
13
13
|
validator: MaybeAsyncValidator<unknown, TValues> | StandardSchemaV1<unknown, TValues>,
|
|
14
|
-
options: FormOptions<TValues>,
|
|
15
|
-
): UseFormReturn<TValues>;
|
|
14
|
+
options: FormOptions<TValues, TResult>,
|
|
15
|
+
): UseFormReturn<TValues, TResult>;
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
+
`TResult` is the value `handleSubmit` resolves to on success. It is the form values unless your `onSubmit` returns a `Result<U, ValidationError[]>`, in which case it is `U`; TypeScript infers it from `onSubmit`.
|
|
19
|
+
|
|
20
|
+
**Explicit type arguments.** `useForm<T>(…)` with only `T` given leaves `TResult` at its default, the form values, so an `onSubmit` that returns `Result<U, …>` is a type error. Write `useForm(schema, …)` and let both be inferred, or give both: `useForm<T, U>(…)`. With explicit `useForm<T, U>`, pass an `onSubmit` that returns a `Result`: an `onSubmit` that returns nothing (for example a forgotten `return`) is a type error, and with no `onSubmit` at all the `ok` value is not checked. It is the form values, typed `U`.
|
|
21
|
+
|
|
18
22
|
### Parameters
|
|
19
23
|
|
|
20
24
|
#### validator
|
|
@@ -48,16 +52,24 @@ const validator = v.object({
|
|
|
48
52
|
|
|
49
53
|
#### options
|
|
50
54
|
|
|
51
|
-
Type: `FormOptions<TValues>`
|
|
55
|
+
Type: `FormOptions<TValues, TResult>`
|
|
52
56
|
|
|
53
57
|
Configuration object.
|
|
54
58
|
|
|
55
59
|
```typescript
|
|
56
60
|
{
|
|
57
|
-
initialValues: TValues
|
|
58
|
-
|
|
61
|
+
initialValues: NoInfer<TValues>;
|
|
62
|
+
// Returning nothing is allowed only when TResult is the form values; see onSubmit below
|
|
63
|
+
onSubmit?:
|
|
64
|
+
| ((values: TValues) => void | Promise<void>)
|
|
65
|
+
| ((values: TValues) => Result<TResult, ValidationError[]> | Promise<Result<TResult, ValidationError[]>>);
|
|
59
66
|
validationMode?: "live" | "blur" | "mount" | "submit";
|
|
60
|
-
fieldValidators?:
|
|
67
|
+
fieldValidators?: {
|
|
68
|
+
[K in ExtractFieldPaths<TValues>]?: (
|
|
69
|
+
value: FieldTypeAtPath<TValues, K>,
|
|
70
|
+
values: TValues,
|
|
71
|
+
) => string | undefined | Promise<string | undefined>;
|
|
72
|
+
};
|
|
61
73
|
onValuesChange?: (values: TValues, prevValues: TValues) => void;
|
|
62
74
|
onFieldChange?: (field: string, value: unknown, values: TValues) => void;
|
|
63
75
|
}
|
|
@@ -75,10 +87,10 @@ Configuration options for useForm.
|
|
|
75
87
|
|
|
76
88
|
#### initialValues
|
|
77
89
|
|
|
78
|
-
Type: `TValues
|
|
90
|
+
Type: `NoInfer<TValues>`
|
|
79
91
|
Required
|
|
80
92
|
|
|
81
|
-
Initial values for form fields. Used when form is reset.
|
|
93
|
+
Initial values for form fields. Used when form is reset. The values type comes from the validator or schema, not from `initialValues`.
|
|
82
94
|
|
|
83
95
|
```typescript
|
|
84
96
|
initialValues: {
|
|
@@ -89,17 +101,28 @@ initialValues: {
|
|
|
89
101
|
|
|
90
102
|
#### onSubmit
|
|
91
103
|
|
|
92
|
-
Type: `(values: TValues) => void | Promise<void
|
|
104
|
+
Type: `(values: TValues) => void | Promise<void>`, or `(values: TValues) => Result<TResult, ValidationError[]> | Promise<Result<TResult, ValidationError[]>>`
|
|
93
105
|
Optional
|
|
94
106
|
|
|
95
|
-
Callback invoked when form is submitted with valid data.
|
|
107
|
+
Callback invoked when form is submitted with valid data. It returns nothing on every path, or a `Result` on every path. Returning nothing is allowed only when `TResult` is the form values.
|
|
96
108
|
|
|
97
109
|
```typescript
|
|
110
|
+
// Return nothing: handleSubmit resolves with the validated values
|
|
98
111
|
onSubmit: async (values) => {
|
|
99
112
|
await api.submit(values);
|
|
100
113
|
};
|
|
114
|
+
|
|
115
|
+
// Return a Result: ok becomes handleSubmit's result, err lands on the form
|
|
116
|
+
onSubmit: async (values) => {
|
|
117
|
+
const res = await api.register(values); // Result<User, ValidationError[]>
|
|
118
|
+
return res;
|
|
119
|
+
};
|
|
101
120
|
```
|
|
102
121
|
|
|
122
|
+
An `err` is placed on the form like `setServerErrors`: per-path errors on their fields, a path-`[]` error as the submit error.
|
|
123
|
+
|
|
124
|
+
**Breaking change: a value that is neither `undefined` nor a `Result` is an error.** If `onSubmit` returns anything else, `handleSubmit` resolves to the generic submit error (`Something went wrong. Please try again.`) and logs `console.error('Form submission error:', error)`. Before, it resolved `ok(values)`. The usual trap is a prop typed `(v: T) => void` that the parent fills with `(v) => api.save(v)`: that returns a `Response` or `mutateAsync`'s data, type-checks, and then fails at runtime. Return nothing (`async (v) => { await save(v); }`) or return a `Result`.
|
|
125
|
+
|
|
103
126
|
#### validationMode
|
|
104
127
|
|
|
105
128
|
Type: `"live" | "blur" | "mount" | "submit"`
|
|
@@ -206,7 +229,7 @@ form.touched.password; // false
|
|
|
206
229
|
|
|
207
230
|
Type: `Record<FieldPath, string>`
|
|
208
231
|
|
|
209
|
-
Combined client, field validator, and server errors. Server errors take highest precedence (server > field > client).
|
|
232
|
+
Combined client, field validator, and server errors. Server errors take highest precedence (server > field > client). The submit error shows at `form.errors._root` (`ROOT_ERROR_KEY`).
|
|
210
233
|
|
|
211
234
|
```typescript
|
|
212
235
|
form.errors.email; // "Email is required"
|
|
@@ -227,7 +250,7 @@ form.clientErrors.email; // "Invalid email format"
|
|
|
227
250
|
|
|
228
251
|
Type: `Record<FieldPath, string>`
|
|
229
252
|
|
|
230
|
-
|
|
253
|
+
Errors from the server: set by `setServerErrors(...)`, or by `onSubmit` returning `err`. The submit error (a server error at path `[]`) shows at `serverErrors._root`.
|
|
231
254
|
|
|
232
255
|
```typescript
|
|
233
256
|
form.serverErrors.username; // "Username already taken"
|
|
@@ -237,7 +260,7 @@ form.serverErrors.username; // "Username already taken"
|
|
|
237
260
|
|
|
238
261
|
Type: `boolean`
|
|
239
262
|
|
|
240
|
-
True when there are no validation errors.
|
|
263
|
+
True when there are no validation errors. The submit error (a server error at path `[]`) is not a validation error and does not count: a form whose submission failed stays valid, so the user can retry.
|
|
241
264
|
|
|
242
265
|
```typescript
|
|
243
266
|
<button disabled={!form.isValid}>Submit</button>
|
|
@@ -309,7 +332,7 @@ The `errors` object is a merged view of three separate error layers. When multip
|
|
|
309
332
|
| ----------- | ----------------- | -------------- | ------------------------------------------------------------------------------ |
|
|
310
333
|
| 1 (lowest) | Schema validation | `clientErrors` | Schema validator runs (on change, blur, mount, or submit depending on mode) |
|
|
311
334
|
| 2 | Field validators | `fieldErrors` | `fieldValidators` option runs for a field (after schema passes for that field) |
|
|
312
|
-
| 3 (highest) | Server errors | `serverErrors` | You call `setServerErrors(...)`
|
|
335
|
+
| 3 (highest) | Server errors | `serverErrors` | You call `setServerErrors(...)`, or `onSubmit` returns `err` |
|
|
313
336
|
|
|
314
337
|
The merge is straightforward -- for each field path, the highest-priority non-empty error wins:
|
|
315
338
|
|
|
@@ -326,7 +349,8 @@ const errors = {
|
|
|
326
349
|
|
|
327
350
|
- `clientErrors` -- replaced on every schema validation run (the entire object is swapped)
|
|
328
351
|
- `fieldErrors` -- cleared per-field when the field validator re-runs or the field's schema error reappears
|
|
329
|
-
- `serverErrors` -- auto-cleared per-field when the user edits the affected field; bulk-cleared on `clearServerErrors()` or new `handleSubmit`
|
|
352
|
+
- `serverErrors` -- auto-cleared per-field when the user edits the affected field, and on the groups that contain it (editing `address.city` clears a server error on `address`); bulk-cleared on `clearServerErrors()` or new `handleSubmit`
|
|
353
|
+
- the submit error (`_root`) -- cleared by any value change, `clearServerErrors()`, `resetForm()`, and at the start of each submit. It does not count toward `isValid`
|
|
330
354
|
|
|
331
355
|
A server error stays visible until the user changes the field, even if client validation passes. That's intentional -- the server said it's wrong, and only editing should dismiss it.
|
|
332
356
|
|
|
@@ -432,23 +456,25 @@ form.setValues({
|
|
|
432
456
|
Set server-side validation errors.
|
|
433
457
|
|
|
434
458
|
```typescript
|
|
435
|
-
setServerErrors(errors:
|
|
459
|
+
setServerErrors(errors: ValidationError[]): void
|
|
436
460
|
```
|
|
437
461
|
|
|
438
462
|
**Parameters:**
|
|
439
463
|
|
|
440
|
-
- `errors` -
|
|
464
|
+
- `errors` - `ValidationError[]`, each `{ path, message }`
|
|
441
465
|
|
|
442
466
|
**Example:**
|
|
443
467
|
|
|
444
468
|
```typescript
|
|
445
|
-
form.setServerErrors(
|
|
446
|
-
email: 'Email already exists',
|
|
447
|
-
username: 'Username taken',
|
|
448
|
-
|
|
469
|
+
form.setServerErrors([
|
|
470
|
+
{ path: ['email'], message: 'Email already exists' },
|
|
471
|
+
{ path: ['username'], message: 'Username taken' },
|
|
472
|
+
// path [] is the submit error: it describes the attempt, not a field
|
|
473
|
+
{ path: [], message: 'Network error. Please try again.' },
|
|
474
|
+
]);
|
|
449
475
|
```
|
|
450
476
|
|
|
451
|
-
Server errors automatically clear when affected fields change.
|
|
477
|
+
Per-path errors land on their fields, under the same keys as client errors, and mark those paths touched. A path-`[]` error becomes the submit error, shown at `form.errors._root`. Server errors automatically clear when affected fields change (and on the groups that contain them); the submit error clears on any value change.
|
|
452
478
|
|
|
453
479
|
### clearServerErrors
|
|
454
480
|
|
|
@@ -469,14 +495,21 @@ form.clearServerErrors();
|
|
|
469
495
|
Submit form with validation. Returns a Railway `Result` so you can pattern-match on the outcome.
|
|
470
496
|
|
|
471
497
|
```typescript
|
|
472
|
-
handleSubmit(e?:
|
|
498
|
+
handleSubmit(e?: SyntheticEvent): Promise<Result<TResult, ValidationError[]>>
|
|
473
499
|
```
|
|
474
500
|
|
|
475
501
|
**Parameters:**
|
|
476
502
|
|
|
477
|
-
- `e` - Optional
|
|
503
|
+
- `e` - Optional event. `preventDefault` is always called on it, including when the call shares a running submission.
|
|
504
|
+
|
|
505
|
+
**Returns:** `Promise<Result<TResult, ValidationError[]>>` -- `Ok` with `onSubmit`'s `ok` value (the validated values when `onSubmit` returns nothing or is absent), `Err` with validation errors or `onSubmit`'s `err` on failure.
|
|
506
|
+
|
|
507
|
+
**It never rejects.** A throw in the schema validator, a field validator or `onSubmit`, or an `onSubmit` value that is neither `undefined` nor a `Result`, is logged with `console.error('Form submission error:', error)` and resolves to `err([{ path: [], message: 'Something went wrong. Please try again.' }])`. That error becomes the submit error at `form.errors._root`, and `isSubmitting` and `isValidating` reset.
|
|
508
|
+
|
|
509
|
+
**Overlapping submits:**
|
|
478
510
|
|
|
479
|
-
|
|
511
|
+
- Same values as the running submission: the call shares its promise, so `onSubmit` does not run twice on a double-click during a slow request.
|
|
512
|
+
- Different values: the call waits for the running submission, then submits the latest values. At most one follow-up waits, so auto-save does not miss edits made during a save.
|
|
480
513
|
|
|
481
514
|
**What it does:**
|
|
482
515
|
|
|
@@ -485,7 +518,7 @@ handleSubmit(e?: FormEvent): Promise<Result<TValues, ValidationError[]>>
|
|
|
485
518
|
3. Clears existing server errors
|
|
486
519
|
4. Runs schema validation (awaits if async)
|
|
487
520
|
5. If schema passes and `fieldValidators` are configured, runs all field validators in parallel
|
|
488
|
-
6. If everything passes, calls `onSubmit` (if provided)
|
|
521
|
+
6. If everything passes, calls `onSubmit` (if provided); an `err` it returns is placed on the form
|
|
489
522
|
7. Returns the `Result`
|
|
490
523
|
|
|
491
524
|
**Example:**
|
|
@@ -494,17 +527,19 @@ handleSubmit(e?: FormEvent): Promise<Result<TValues, ValidationError[]>>
|
|
|
494
527
|
// Use onSubmit callback (void discards the Promise for React 19 compatibility)
|
|
495
528
|
<form onSubmit={(e) => void form.handleSubmit(e)}>{/* fields */}</form>
|
|
496
529
|
|
|
497
|
-
// Advanced:
|
|
530
|
+
// Advanced: onSubmit returns a Result, handleSubmit resolves with it
|
|
498
531
|
import { match } from "@railway-ts/pipelines/result";
|
|
499
532
|
|
|
533
|
+
const form = useForm(schema, {
|
|
534
|
+
initialValues: { email: "", password: "" },
|
|
535
|
+
onSubmit: async (values) => registerUser(values), // Result<User, ValidationError[]>
|
|
536
|
+
});
|
|
537
|
+
|
|
500
538
|
const result = await form.handleSubmit();
|
|
501
539
|
match(result, {
|
|
502
|
-
ok: (
|
|
503
|
-
console.log("Submitted:", values);
|
|
504
|
-
navigate("/success");
|
|
505
|
-
},
|
|
540
|
+
ok: (user) => navigate(`/welcome/${user.id}`),
|
|
506
541
|
err: (errors) => {
|
|
507
|
-
console.error("
|
|
542
|
+
console.error("Submission errors:", errors);
|
|
508
543
|
scrollToFirstError();
|
|
509
544
|
},
|
|
510
545
|
});
|
|
@@ -1481,6 +1516,8 @@ function SubmitButton({ form }: Props) {
|
|
|
1481
1516
|
}
|
|
1482
1517
|
```
|
|
1483
1518
|
|
|
1519
|
+
`UseFormReturn<V>` accepts any form of shape `V`, whatever its `onSubmit` returns. Its `handleSubmit` resolves `Result<unknown, ValidationError[]>`. A component that reads the `ok` value writes `UseFormReturn<V, V>`, or `UseFormReturn<V, U>` for a form whose `onSubmit` returns `Result<U, …>`.
|
|
1520
|
+
|
|
1484
1521
|
### InferSchemaType
|
|
1485
1522
|
|
|
1486
1523
|
Extract TypeScript type from validator schema. Works with nested objects, arrays, and composed schemas.
|
package/docs/GETTING_STARTED.md
CHANGED
|
@@ -183,11 +183,15 @@ const form = useForm(validator, {
|
|
|
183
183
|
|
|
184
184
|
## Step 5: Submission and Server Errors
|
|
185
185
|
|
|
186
|
-
When the user submits, `handleSubmit` validates the form, marks all fields as touched, and calls your `onSubmit` callback if validation passes.
|
|
186
|
+
When the user submits, `handleSubmit` validates the form, marks all fields as touched, and calls your `onSubmit` callback if validation passes. `onSubmit` can return a `Result`: an `err` of `ValidationError[]` lands on the form and displays through the same `form.errors` object:
|
|
187
187
|
|
|
188
188
|
```tsx
|
|
189
|
+
import { err, ok } from '@railway-ts/pipelines/result';
|
|
190
|
+
|
|
191
|
+
import type { ValidationError } from '@railway-ts/pipelines/schema';
|
|
192
|
+
|
|
189
193
|
function RegistrationForm() {
|
|
190
|
-
const form = useForm
|
|
194
|
+
const form = useForm(registrationSchema, {
|
|
191
195
|
initialValues: { username: '', email: '', password: '' },
|
|
192
196
|
onSubmit: async (values) => {
|
|
193
197
|
const response = await fetch('/api/register', {
|
|
@@ -197,13 +201,12 @@ function RegistrationForm() {
|
|
|
197
201
|
});
|
|
198
202
|
|
|
199
203
|
if (!response.ok) {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
form.setServerErrors(errors);
|
|
203
|
-
return;
|
|
204
|
+
// [{ path: ['username'], message: 'Username already taken' }, ...]
|
|
205
|
+
return err((await response.json()) as ValidationError[]);
|
|
204
206
|
}
|
|
205
207
|
|
|
206
208
|
window.location.href = '/dashboard';
|
|
209
|
+
return ok(values);
|
|
207
210
|
},
|
|
208
211
|
});
|
|
209
212
|
|
|
@@ -230,11 +233,13 @@ Three things to know about server errors:
|
|
|
230
233
|
|
|
231
234
|
1. **They auto-clear** -- when the user edits a field, its server error disappears
|
|
232
235
|
2. **They win** -- if a field has both a client error and a server error, the server error is displayed (server > fieldValidator > client)
|
|
233
|
-
3. **
|
|
236
|
+
3. **The submit error** -- a server error at path `[]` is not tied to a field: it describes the submission itself (e.g., network errors, rate limiting). It shows at `form.errors._root` (`ROOT_ERROR_KEY`, from `@railway-ts/pipelines/schema`), does not count toward `isValid`, and clears on any edit
|
|
237
|
+
|
|
238
|
+
You can also set server errors yourself, for example from a mutation callback: `form.setServerErrors([{ path: ['username'], message: 'Username already taken' }])` takes the same `ValidationError[]`.
|
|
234
239
|
|
|
235
|
-
`handleSubmit` accepts an optional
|
|
240
|
+
`handleSubmit` accepts an optional event. When passed, it calls `e.preventDefault()` automatically. You can also call `handleSubmit()` without an event -- useful for programmatic submission (e.g., after a "Next" button in a wizard). It never rejects: if a validator or `onSubmit` throws, it logs the error and resolves to an `err` that shows as the submit error ("Something went wrong. Please try again."). An `onSubmit` must return nothing or a `Result`; any other value is treated the same way.
|
|
236
241
|
|
|
237
|
-
`handleSubmit` also
|
|
242
|
+
`handleSubmit` also resolves to a `Result`, so you can pattern-match on the outcome where you call it, for example to navigate once `onSubmit` returns `ok`. See [Recipes](./RECIPES.md#pattern-matching-submit-results) for that pattern.
|
|
238
243
|
|
|
239
244
|
> **React 19 note:** React 19 form actions expect `onSubmit` to not return a Promise. Use `(e) => void form.handleSubmit(e)` to satisfy the type checker.
|
|
240
245
|
|
package/docs/RECIPES.md
CHANGED
|
@@ -41,9 +41,10 @@ Patterns and techniques. Each recipe is self-contained.
|
|
|
41
41
|
|
|
42
42
|
**Problem:** You're building a create/edit form that talks to an API. The server might reject the data (duplicate email, username taken), and you need those errors to appear on the correct fields.
|
|
43
43
|
|
|
44
|
-
**Solution:** Use `onSubmit` to call the API
|
|
44
|
+
**Solution:** Use `onSubmit` to call the API and return an `err` built from the backend's `ValidationError[]`: it lands on the matching fields. Server errors auto-clear when the user edits the affected field.
|
|
45
45
|
|
|
46
46
|
```tsx
|
|
47
|
+
import { err, ok } from '@railway-ts/pipelines/result';
|
|
47
48
|
import {
|
|
48
49
|
object,
|
|
49
50
|
string,
|
|
@@ -55,6 +56,7 @@ import {
|
|
|
55
56
|
email,
|
|
56
57
|
ROOT_ERROR_KEY,
|
|
57
58
|
type InferSchemaType,
|
|
59
|
+
type ValidationError,
|
|
58
60
|
} from '@railway-ts/pipelines/schema';
|
|
59
61
|
import { useForm } from '@railway-ts/use-form';
|
|
60
62
|
|
|
@@ -67,23 +69,28 @@ const userSchema = object({
|
|
|
67
69
|
type UserForm = InferSchemaType<typeof userSchema>;
|
|
68
70
|
|
|
69
71
|
function CreateUserForm() {
|
|
70
|
-
const form = useForm
|
|
72
|
+
const form = useForm(userSchema, {
|
|
71
73
|
initialValues: { username: '', email: '', bio: '' },
|
|
72
74
|
onSubmit: async (values) => {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
75
|
+
let response: Response;
|
|
76
|
+
try {
|
|
77
|
+
response = await fetch('/api/users', {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: { 'Content-Type': 'application/json' },
|
|
80
|
+
body: JSON.stringify(values),
|
|
81
|
+
});
|
|
82
|
+
} catch {
|
|
83
|
+
// path [] is the submit error, shown at form.errors[ROOT_ERROR_KEY]
|
|
84
|
+
return err([{ path: [], message: 'Network error. Please try again.' }]);
|
|
85
|
+
}
|
|
78
86
|
|
|
79
87
|
if (!response.ok) {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
form.setServerErrors(errors);
|
|
83
|
-
return;
|
|
88
|
+
// e.g. [{ path: ['email'], message: 'Email already exists' }, { path: ['username'], message: 'Username taken' }]
|
|
89
|
+
return err((await response.json()) as ValidationError[]);
|
|
84
90
|
}
|
|
85
91
|
|
|
86
|
-
window.location.
|
|
92
|
+
window.location.assign('/users');
|
|
93
|
+
return ok(values);
|
|
87
94
|
},
|
|
88
95
|
});
|
|
89
96
|
|
|
@@ -121,12 +128,14 @@ function CreateUserForm() {
|
|
|
121
128
|
}
|
|
122
129
|
```
|
|
123
130
|
|
|
124
|
-
For form-level errors (network failures, rate limiting), use `ROOT_ERROR_KEY`:
|
|
131
|
+
For form-level errors (network failures, rate limiting), use a path-`[]` error. It is the submit error: it shows at `form.errors[ROOT_ERROR_KEY]`, does not count toward `isValid`, and clears on any edit. Outside `onSubmit`, set it with `setServerErrors`:
|
|
125
132
|
|
|
126
133
|
```typescript
|
|
127
|
-
form.setServerErrors({ [
|
|
134
|
+
form.setServerErrors([{ path: [], message: 'Network error. Please try again.' }]);
|
|
128
135
|
```
|
|
129
136
|
|
|
137
|
+
If `onSubmit` throws instead, `handleSubmit` logs the error and sets the generic submit error, "Something went wrong. Please try again."
|
|
138
|
+
|
|
130
139
|
---
|
|
131
140
|
|
|
132
141
|
## Nested Objects
|
|
@@ -1012,13 +1021,14 @@ const form = useForm(schema, {
|
|
|
1012
1021
|
| ----------- | ----------------- | -------------- | ------------------------------------------------------------------------------ |
|
|
1013
1022
|
| 1 (lowest) | Schema validation | `clientErrors` | Schema validator runs (on change, blur, mount, or submit depending on mode) |
|
|
1014
1023
|
| 2 | Field validators | `fieldErrors` | `fieldValidators` option runs for a field (after schema passes for that field) |
|
|
1015
|
-
| 3 (highest) | Server errors | `serverErrors` | You call `setServerErrors(...)`
|
|
1024
|
+
| 3 (highest) | Server errors | `serverErrors` | You call `setServerErrors(...)`, or `onSubmit` returns `err` |
|
|
1016
1025
|
|
|
1017
1026
|
**When each layer gets cleared:**
|
|
1018
1027
|
|
|
1019
1028
|
- `clientErrors` -- replaced on every schema validation run
|
|
1020
1029
|
- `fieldErrors` -- cleared per-field when the field validator re-runs or the field's schema error reappears
|
|
1021
|
-
- `serverErrors` -- auto-cleared per-field when the user edits the affected field; bulk-cleared on `clearServerErrors()` or new `handleSubmit`
|
|
1030
|
+
- `serverErrors` -- auto-cleared per-field when the user edits the affected field, and on any group that contains it (editing `address.city` clears a server error on `address`); bulk-cleared on `clearServerErrors()` or new `handleSubmit`
|
|
1031
|
+
- the submit error (`_root`) -- cleared by any edit, `clearServerErrors()`, `resetForm()`, and at the start of each submit
|
|
1022
1032
|
|
|
1023
1033
|
A server error stays visible until the user changes the field, even if client validation passes. That's intentional -- the server said it's wrong, and only editing should dismiss it.
|
|
1024
1034
|
|
|
@@ -1181,29 +1191,32 @@ Field validators return `undefined` for valid, or an error message string for in
|
|
|
1181
1191
|
|
|
1182
1192
|
## Pattern-Matching Submit Results
|
|
1183
1193
|
|
|
1184
|
-
**Problem:** You want to
|
|
1194
|
+
**Problem:** You want to act on the submit outcome where you call `handleSubmit` -- for example, to navigate on success or log errors.
|
|
1185
1195
|
|
|
1186
|
-
**Solution:** `
|
|
1196
|
+
**Solution:** Have `onSubmit` return a `Result`. `handleSubmit` resolves to it: `onSubmit`'s `ok` value, or its `err`, which also lands on the form. It never rejects. Use `match` from `@railway-ts/pipelines/result` to branch on the outcome.
|
|
1187
1197
|
|
|
1188
1198
|
```tsx
|
|
1189
|
-
import { match } from '@railway-ts/pipelines/result';
|
|
1199
|
+
import { match, type Result } from '@railway-ts/pipelines/result';
|
|
1200
|
+
|
|
1201
|
+
import type { ValidationError } from '@railway-ts/pipelines/schema';
|
|
1202
|
+
|
|
1203
|
+
type User = { id: string; email: string };
|
|
1204
|
+
declare const navigate: (to: string) => void;
|
|
1205
|
+
declare const registerUser: (values: { email: string; password: string }) => Promise<Result<User, ValidationError[]>>;
|
|
1190
1206
|
|
|
1191
1207
|
function RegistrationForm() {
|
|
1192
1208
|
const form = useForm(registrationSchema, {
|
|
1193
1209
|
initialValues: { email: '', password: '' },
|
|
1194
|
-
|
|
1210
|
+
onSubmit: async (values) => registerUser(values),
|
|
1195
1211
|
});
|
|
1196
1212
|
|
|
1197
1213
|
const handleSave = async () => {
|
|
1198
1214
|
const result = await form.handleSubmit();
|
|
1199
1215
|
|
|
1200
1216
|
match(result, {
|
|
1201
|
-
ok: (
|
|
1202
|
-
console.log('Validated data:', values);
|
|
1203
|
-
// Navigate, show toast, etc.
|
|
1204
|
-
},
|
|
1217
|
+
ok: (user) => navigate(`/welcome/${user.id}`),
|
|
1205
1218
|
err: (errors) => {
|
|
1206
|
-
console.error('
|
|
1219
|
+
console.error('Submit failed:', errors);
|
|
1207
1220
|
// Log to analytics, show banner, etc.
|
|
1208
1221
|
},
|
|
1209
1222
|
});
|
|
@@ -1224,24 +1237,6 @@ function RegistrationForm() {
|
|
|
1224
1237
|
}
|
|
1225
1238
|
```
|
|
1226
1239
|
|
|
1227
|
-
You can also combine `onSubmit` (for the main action) with the returned `Result` (for side effects):
|
|
1228
|
-
|
|
1229
|
-
```typescript
|
|
1230
|
-
const form = useForm(schema, {
|
|
1231
|
-
initialValues: {/* ... */},
|
|
1232
|
-
onSubmit: async (values) => {
|
|
1233
|
-
await api.createUser(values);
|
|
1234
|
-
},
|
|
1235
|
-
});
|
|
1236
|
-
|
|
1237
|
-
// Later, in a handler:
|
|
1238
|
-
const result = await form.handleSubmit();
|
|
1239
|
-
match(result, {
|
|
1240
|
-
ok: () => navigate('/dashboard'),
|
|
1241
|
-
err: () => scrollToFirstError(),
|
|
1242
|
-
});
|
|
1243
|
-
```
|
|
1244
|
-
|
|
1245
1240
|
---
|
|
1246
1241
|
|
|
1247
1242
|
## Custom Field Components
|
|
@@ -1695,9 +1690,12 @@ import {
|
|
|
1695
1690
|
minLength,
|
|
1696
1691
|
ROOT_ERROR_KEY,
|
|
1697
1692
|
type InferSchemaType,
|
|
1693
|
+
type ValidationError,
|
|
1698
1694
|
} from '@railway-ts/pipelines/schema';
|
|
1699
1695
|
import { useForm } from '@railway-ts/use-form';
|
|
1700
1696
|
|
|
1697
|
+
import type { SyntheticEvent } from 'react';
|
|
1698
|
+
|
|
1701
1699
|
// --- Schema ---
|
|
1702
1700
|
|
|
1703
1701
|
const schema = chain(
|
|
@@ -1711,17 +1709,18 @@ const schema = chain(
|
|
|
1711
1709
|
);
|
|
1712
1710
|
|
|
1713
1711
|
type Registration = InferSchemaType<typeof schema>;
|
|
1712
|
+
type User = { id: string; username: string };
|
|
1714
1713
|
|
|
1715
1714
|
// --- API layer ---
|
|
1716
1715
|
|
|
1717
1716
|
const checkUsername = (username: string) =>
|
|
1718
1717
|
fromPromise<{ available: boolean }>(
|
|
1719
1718
|
fetch(`/api/check-username?u=${encodeURIComponent(username)}`).then((res) =>
|
|
1720
|
-
res.ok ? res.json() : Promise.reject(`HTTP ${res.status}`),
|
|
1719
|
+
res.ok ? (res.json() as Promise<{ available: boolean }>) : Promise.reject(new Error(`HTTP ${res.status}`)),
|
|
1721
1720
|
),
|
|
1722
1721
|
);
|
|
1723
1722
|
|
|
1724
|
-
const registerUser = async (values: Registration): Promise<Result<
|
|
1723
|
+
const registerUser = async (values: Registration): Promise<Result<User, ValidationError[]>> => {
|
|
1725
1724
|
const result = await fromPromise(
|
|
1726
1725
|
fetch('/api/register', {
|
|
1727
1726
|
method: 'POST',
|
|
@@ -1730,18 +1729,19 @@ const registerUser = async (values: Registration): Promise<Result<void, Record<s
|
|
|
1730
1729
|
}),
|
|
1731
1730
|
);
|
|
1732
1731
|
|
|
1733
|
-
|
|
1732
|
+
// path [] is the submit error, shown at form.errors[ROOT_ERROR_KEY]
|
|
1733
|
+
if (!result.ok) return err([{ path: [], message: 'Network error. Please try again.' }]);
|
|
1734
1734
|
|
|
1735
1735
|
const res = result.value;
|
|
1736
|
-
if (!res.ok) return err((await res.json()) as
|
|
1736
|
+
if (!res.ok) return err((await res.json()) as ValidationError[]);
|
|
1737
1737
|
|
|
1738
|
-
return ok(
|
|
1738
|
+
return ok((await res.json()) as User);
|
|
1739
1739
|
};
|
|
1740
1740
|
|
|
1741
1741
|
// --- Component ---
|
|
1742
1742
|
|
|
1743
1743
|
export function RegistrationForm() {
|
|
1744
|
-
const form = useForm
|
|
1744
|
+
const form = useForm(schema, {
|
|
1745
1745
|
initialValues: {
|
|
1746
1746
|
username: '',
|
|
1747
1747
|
email: '',
|
|
@@ -1757,19 +1757,20 @@ export function RegistrationForm() {
|
|
|
1757
1757
|
});
|
|
1758
1758
|
},
|
|
1759
1759
|
},
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
match(result, {
|
|
1763
|
-
ok: () => {
|
|
1764
|
-
window.location.reassign = '/welcome';
|
|
1765
|
-
},
|
|
1766
|
-
err: (errors) => form.setServerErrors(errors),
|
|
1767
|
-
});
|
|
1768
|
-
},
|
|
1760
|
+
// The returned Result is handleSubmit's result; an err lands on the form
|
|
1761
|
+
onSubmit: (values) => registerUser(values),
|
|
1769
1762
|
});
|
|
1770
1763
|
|
|
1764
|
+
const handleRegister = async (e: SyntheticEvent) => {
|
|
1765
|
+
match(await form.handleSubmit(e), {
|
|
1766
|
+
ok: (user) => window.location.assign(`/welcome/${user.id}`),
|
|
1767
|
+
// Already on the form: field errors under their paths, a network failure at errors[ROOT_ERROR_KEY]
|
|
1768
|
+
err: () => {},
|
|
1769
|
+
});
|
|
1770
|
+
};
|
|
1771
|
+
|
|
1771
1772
|
return (
|
|
1772
|
-
<form onSubmit={(e) => void
|
|
1773
|
+
<form onSubmit={(e) => void handleRegister(e)}>
|
|
1773
1774
|
<input {...form.getFieldProps('username')} />
|
|
1774
1775
|
{form.validatingFields.username && <span>Checking...</span>}
|
|
1775
1776
|
{form.getFieldError('username') && <span>{form.getFieldError('username')}</span>}
|
|
@@ -1798,9 +1799,9 @@ This form demonstrates:
|
|
|
1798
1799
|
- **Schema validation** -- `chain` + `nonEmpty` + `email` + `minLength`
|
|
1799
1800
|
- **Cross-field validation** -- `refineAt` for password confirmation
|
|
1800
1801
|
- **Per-field async validation** -- `fieldValidators` for username availability with `validatingFields` loading state
|
|
1801
|
-
- **Server errors** -- `
|
|
1802
|
-
- **Result handling** -- `fromPromise` for both API calls, explicit `ok`/`err` for registration, `match` for branching
|
|
1803
|
-
- **React 19 compatibility** -- `(e) => void
|
|
1802
|
+
- **Server errors** -- `onSubmit` returns the API's `err(ValidationError[])`, which lands on the fields; a network failure is a path-`[]` submit error. Both auto-clear on edit
|
|
1803
|
+
- **Result handling** -- `fromPromise` for both API calls, explicit `ok`/`err` for registration, `match` for branching, including on `handleSubmit`'s result to navigate on success
|
|
1804
|
+
- **React 19 compatibility** -- `(e) => void handleRegister(e)` pattern
|
|
1804
1805
|
|
|
1805
1806
|
---
|
|
1806
1807
|
|
|
@@ -1820,6 +1821,7 @@ import {
|
|
|
1820
1821
|
minLength,
|
|
1821
1822
|
ROOT_ERROR_KEY,
|
|
1822
1823
|
type InferSchemaType,
|
|
1824
|
+
type ValidationError,
|
|
1823
1825
|
} from '@railway-ts/pipelines/schema';
|
|
1824
1826
|
import { useForm } from '@railway-ts/use-form';
|
|
1825
1827
|
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
|
@@ -1843,11 +1845,11 @@ type Registration = InferSchemaType<typeof schema>;
|
|
|
1843
1845
|
|
|
1844
1846
|
const checkUsername = (username: string): Promise<{ available: boolean }> =>
|
|
1845
1847
|
fetch(`/api/check-username?u=${encodeURIComponent(username)}`).then((res) =>
|
|
1846
|
-
res.ok ? res.json() : Promise.reject(`HTTP ${res.status}`),
|
|
1848
|
+
res.ok ? res.json() : Promise.reject(new Error(`HTTP ${res.status}`)),
|
|
1847
1849
|
);
|
|
1848
1850
|
|
|
1849
1851
|
class ApiValidationError extends Error {
|
|
1850
|
-
constructor(public fieldErrors:
|
|
1852
|
+
constructor(public fieldErrors: ValidationError[]) {
|
|
1851
1853
|
super('Validation failed');
|
|
1852
1854
|
}
|
|
1853
1855
|
}
|
|
@@ -1859,7 +1861,7 @@ const registerUser = async (values: Registration): Promise<void> => {
|
|
|
1859
1861
|
body: JSON.stringify(values),
|
|
1860
1862
|
});
|
|
1861
1863
|
|
|
1862
|
-
if (!res.ok) throw new ApiValidationError(await res.json());
|
|
1864
|
+
if (!res.ok) throw new ApiValidationError((await res.json()) as ValidationError[]);
|
|
1863
1865
|
};
|
|
1864
1866
|
|
|
1865
1867
|
// --- Component ---
|
|
@@ -1875,9 +1877,8 @@ export function RegistrationForm() {
|
|
|
1875
1877
|
if (error instanceof ApiValidationError) {
|
|
1876
1878
|
form.setServerErrors(error.fieldErrors);
|
|
1877
1879
|
} else {
|
|
1878
|
-
form.
|
|
1879
|
-
|
|
1880
|
-
});
|
|
1880
|
+
// path [] is the submit error, shown at form.errors[ROOT_ERROR_KEY]
|
|
1881
|
+
form.setServerErrors([{ path: [], message: 'Network error. Please try again.' }]);
|
|
1881
1882
|
}
|
|
1882
1883
|
},
|
|
1883
1884
|
});
|
|
@@ -1936,7 +1937,7 @@ This form demonstrates:
|
|
|
1936
1937
|
- **Schema validation** -- `chain` + `nonEmpty` + `email` + `minLength`
|
|
1937
1938
|
- **Cross-field validation** -- `refineAt` for password confirmation
|
|
1938
1939
|
- **Per-field async validation** -- `queryClient.fetchQuery` with `staleTime` for caching username checks
|
|
1939
|
-
- **Server errors** -- `ApiValidationError` + `useMutation` `onError` → `setServerErrors`, auto-clear on edit
|
|
1940
|
+
- **Server errors** -- `ApiValidationError` + `useMutation` `onError` → `setServerErrors([...])`, auto-clear on edit
|
|
1940
1941
|
- **React Query integration** -- `useMutation` for submit, `fetchQuery` for field validation
|
|
1941
1942
|
- **React 19 compatibility** -- `(e) => void form.handleSubmit(e)` pattern
|
|
1942
1943
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@railway-ts/use-form",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "React form hook that works with @railway-ts/pipelines to manage form state, validation, and submission.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.mjs",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
],
|
|
21
21
|
"sideEffects": false,
|
|
22
22
|
"engines": {
|
|
23
|
-
"node": ">=
|
|
23
|
+
"node": ">=22.12"
|
|
24
24
|
},
|
|
25
25
|
"scripts": {
|
|
26
26
|
"example": "bun --hot examples/server.ts",
|
|
@@ -54,9 +54,9 @@
|
|
|
54
54
|
"access": "public"
|
|
55
55
|
},
|
|
56
56
|
"peerDependencies": {
|
|
57
|
-
"@railway-ts/pipelines": "^0.
|
|
58
|
-
"react": "^
|
|
59
|
-
"typescript": ">=
|
|
57
|
+
"@railway-ts/pipelines": "^0.3.0",
|
|
58
|
+
"react": "^19.0.0",
|
|
59
|
+
"typescript": ">=6.0"
|
|
60
60
|
},
|
|
61
61
|
"peerDependenciesMeta": {
|
|
62
62
|
"typescript": {
|
|
@@ -65,13 +65,14 @@
|
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
67
|
"@happy-dom/global-registrator": "^21.0.4",
|
|
68
|
-
"@railway-ts/pipelines": "0.
|
|
68
|
+
"@railway-ts/pipelines": "0.3.0",
|
|
69
69
|
"@testing-library/dom": "^10.4.2",
|
|
70
70
|
"@testing-library/jest-dom": "^8.0.0",
|
|
71
71
|
"@testing-library/react": "^16.3.3",
|
|
72
72
|
"@testing-library/user-event": "^14.6.13",
|
|
73
73
|
"@types/react": "^19.3.0",
|
|
74
74
|
"@types/react-dom": "^19.3.0",
|
|
75
|
+
"arktype": "^2.2.10",
|
|
75
76
|
"react": "^19.3.1",
|
|
76
77
|
"react-dom": "^19.3.1",
|
|
77
78
|
"valibot": "^1.5.0",
|