Skip to content
Merged
8 changes: 4 additions & 4 deletions docs/guide/pages-routing/actions-and-forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ The types are inferred from your action's `withValidator()` schema in the compan
| Property / Method | Purpose |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data` / `setData` | Current form values, typed to match the action's body schema. |
| `errors` | Field-level validation errors, keys typed to body field names. |
| `errors` | Field-level validation errors, keyed by body field and by nested paths such as `profile.name` or `contacts.0.email`. |
| `error` | Action error, or `null`. |
| `throwOnError` (option) | Set to `false` to keep authentication and server failures in `form.error` instead of throwing them. |
| `post`, `put`, `patch`, `delete` | Submit the form with that method. In React these are native form action callbacks. |
Expand All @@ -163,11 +163,11 @@ The types are inferred from your action's `withValidator()` schema in the compan
| `recentlySuccessful` | `true` for 2 seconds after a successful submission. Useful for flash messages. |
| `reset(...fields)` | Reset form data to the current defaults (last submitted values after success). Field names autocomplete. Pass `{ initial: true }` first to reset to the values passed to `useForm`. |
| `resetOnSuccess` (option) | When `true`, a successful submit resets defaults to the mount-time values, and form data too unless it was edited during the submit. Useful for create forms that should clear after save. |
| `setError(field, message)` | Set a client-side validation error on a field. |
| `clearErrors(...fields)` | Clear validation errors. Field names autocomplete. |
| `setError(field, message)` | Set a client-side validation error on a field, including a nested path such as `profile.name`. |
| `clearErrors(...fields)` | Clear validation errors. Field names autocomplete. Clearing a parent field also clears the errors of its nested fields. |
| `clearError()` | Clear `error`. |

Use `setError()` for client-side validation. Editing a field clears its error automatically.
Use `setError()` for client-side validation. Editing a value clears its error and the errors of the nested values that changed with it. Fields you did not change keep their errors.

For a native React form, use `form.post`, `form.put`, `form.patch`, or `form.delete` as a native form action. For an awaitable mutation, use `action()`. In Vue, Svelte, and Solid, form submissions return `Promise<void>`; catch thrown errors or use your framework's error handling.

Expand Down
27 changes: 13 additions & 14 deletions packages/react/src/runtime/use-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ import {
useState,
} from 'react';
import {
changedFormErrorKeys,
cloneFormValue,
formErrorKeysWithin,
getValidationErrors,
interpolateRouteParams,
isAbortError,
isCallSiteActionError,
isEqualFormValue,
omitFormErrors,
parseFormResetArgs,
submitAction,
} from 'void/pages-client';
Expand Down Expand Up @@ -189,23 +192,20 @@ export function useForm(

const setData = useCallback(
(field: string, value: unknown) => {
const previousValue = dataRef.current[field];
dataRef.current = { ...dataRef.current, [field]: value };
setDataState(dataRef.current);
if (isEqualFormValue(previousValue, value)) {
return;
}
const previous = dataRef.current;
const next = { ...previous, [field]: value };
dataRef.current = next;
setDataState(next);
const target = callbackOutcomeRef.current ?? outcome;
setErrorEdits((prev) => {
const current = resolveOutcomeErrors(target, prev);
if (!(field in current)) {
const affected = changedFormErrorKeys(current, previous, next);
if (affected.length === 0) {
return prev;
}
const next = { ...current };
delete next[field];
return {
...(prev?.source === target ? prev : { source: target }),
errors: next,
errors: omitFormErrors(current, affected),
};
});
},
Expand Down Expand Up @@ -234,15 +234,14 @@ export function useForm(
const clearErrors = useCallback(
(...fields: ReadonlyArray<string>) => {
const target = callbackOutcomeRef.current ?? outcome;
const data = dataRef.current;
setErrorEdits((prev) => {
const base = prev?.source === target ? prev : { source: target };
if (fields.length === 0) {
return { ...base, errors: EMPTY_ERRORS };
}
const next = { ...resolveOutcomeErrors(target, prev) };
for (const field of fields) {
delete next[field];
}
const current = resolveOutcomeErrors(target, prev);
const next = omitFormErrors(current, formErrorKeysWithin(current, fields, data));
return { ...base, errors: next };
});
},
Expand Down
111 changes: 111 additions & 0 deletions packages/react/test/unit/use-form.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ import type { IslandFormReturn } from '../../src/runtime/use-island-form.ts';
declare module 'void/routes' {
interface PageActionMap {
'/__form-callbacks/notes': { actions: { create: { body: { title: string } } } };
'/__form-nested/contacts': {
body: {
profile: { name: string; email: string };
contacts: Array<{ email: string }>;
};
};
}
}

Expand Down Expand Up @@ -254,6 +260,60 @@ describe('useForm callbacks', () => {
expect(formRef.current!.error).toBe(actionError);
});

it('clears only the errors of the fields a change touched', async () => {
type NestedForm = ReturnType<typeof useForm<'/__form-nested/contacts'>>;
const formRef: FormRef<NestedForm> = { current: null };
function App() {
formRef.current = useForm('/__form-nested/contacts', {
profile: { name: '', email: '' },
contacts: [{ email: '' }, { email: '' }],
});
return null;
}
const router = routerWithVisit(
vi.fn(async () => ({
errors: {
'profile.name': 'Required name',
'profile.email': 'Required email',
'contacts.0.email': 'First email',
'contacts.1.email': 'Second email',
title: 'Unrelated',
},
})),
);
await mountApp(createElement(RouterContext.Provider, { value: router }, createElement(App)));
const form = () => formRef.current!;
const submit = () =>
act(async () => {
startTransition(() => {
form().post(new FormData());
});
});

await submit();
await act(async () => {
form().setData('profile', { name: 'Alex', email: '' });
});
expect(form().errors['profile.name']).toBeUndefined();
expect(form().errors['profile.email']).toBe('Required email');

await act(async () => {
form().setData('contacts', [{ email: '' }, { email: 'alex@example.com' }]);
});
expect(form().errors['contacts.0.email']).toBe('First email');
expect(form().errors['contacts.1.email']).toBeUndefined();

await act(async () => {
form().clearErrors('profile');
});
expect(form().errors).toEqual({ 'contacts.0.email': 'First email', title: 'Unrelated' });

await act(async () => {
form().clearErrors('contacts');
});
expect(form().errors).toEqual({ title: 'Unrelated' });
});

it('fires onSuccess on each successful submit', async () => {
const onSuccess = vi.fn();
const { formRef } = await mountForm(
Expand Down Expand Up @@ -810,3 +870,54 @@ describe('useForm state derivation and error management', () => {
}
});
});

declare module 'void/routes' {
interface PageActionMap {
'/__form-optional/contacts': {
body: { contacts: Array<{ email: string } | undefined> };
};
}
}

describe('error isolation', () => {
it.each([
{
name: 'changes one row while an array-level and two row-level errors exist',
initial: [{ email: '' }, { email: '' }],
updated: [{ email: 'fixed@example.com' }, { email: '' }],
initialErrors: {
contacts: 'At least one valid email required',
'contacts.0.email': 'First email required',
'contacts.1.email': 'Second email required',
},
expectedErrors: { 'contacts.1.email': 'Second email required' },
},
{
name: 'clears the array-level count error after adding an undefined slot',
initial: [undefined],
updated: [undefined, undefined],
initialErrors: { contacts: 'Add a second row' },
expectedErrors: {},
},
])('$name', async ({ initial, updated, initialErrors, expectedErrors }) => {
type OptionalForm = ReturnType<typeof useForm<'/__form-optional/contacts'>>;
const formRef: FormRef<OptionalForm> = { current: null };
function App() {
formRef.current = useForm('/__form-optional/contacts', { contacts: initial });
return null;
}
const router = routerWithVisit(async () => ({ errors: initialErrors }));
await mountApp(createElement(RouterContext.Provider, { value: router }, createElement(App)));
await act(async () => {
startTransition(() => {
formRef.current!.post(new FormData());
});
});
expect(formRef.current!.errors).toEqual(initialErrors);
await act(async () => {
formRef.current!.setData('contacts', updated);
});
expect(formRef.current!.data.contacts).toEqual(updated);
expect(formRef.current!.errors).toEqual(expectedErrors);
});
});
31 changes: 31 additions & 0 deletions packages/react/test/unit/use-form.typecheck.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,44 @@
import { VoidActionError } from 'void/pages-client';
import type { FormState } from 'void/pages-client';
import { useForm } from '../../src/runtime/use-form.ts';

export function checkGenericFieldHelpers<T>(
form: FormState<T, 'setters'>,
field: keyof T & string,
): string | undefined {
form.setError(field, 'Client-side');
form.clearErrors(field);
return form.errors[field];
}

declare module 'void/routes' {
interface PageActionMap {
'/__form-options/notes': { actions: { create: { body: { title: string } } } };
'/__form-options/notes/:id': { body: { title: string }; params: { id: string } };
'/__form-options/nested': {
body: { profile: { name: string }; contacts: Array<{ email: string }> };
};
}
}

export function checkNestedErrorPaths(): void {
const form = useForm('/__form-options/nested', {
profile: { name: '' },
contacts: [{ email: '' }],
});
const name: string | undefined = form.errors['profile.name'];
const email: string | undefined = form.errors['contacts.0.email'];
void name;
void email;
form.setError('profile.name', 'Required name');
form.setError('contacts.0.email', 'Required email');
form.clearErrors('profile', 'contacts', 'contacts.0.email');
// @ts-expect-error Nested error paths must name a field in the action body.
form.setError('profile.missing', 'Invalid');
// @ts-expect-error Array segments must be numeric array indices.
form.clearErrors('contacts.first');
}

export function checkFormOptions(): void {
useForm(
'/__form-options/notes?create',
Expand Down
30 changes: 20 additions & 10 deletions packages/solid/src/runtime/use-form.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { createSignal, createMemo, useContext } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import {
changedFormErrorKeys,
cloneFormValue,
formErrorKeysWithin,
getValidationErrors,
interpolateRouteParams,
isAbortError,
isCallSiteActionError,
isEqualFormValue,
omitFormErrors,
parseFormResetArgs,
submitAction,
} from 'void/pages-client';
Expand Down Expand Up @@ -90,8 +93,18 @@ export function useForm(
});

function setData(field: string, value: unknown) {
// The store can merge the new value into the existing object. Snapshot that field
// before the write and compare against what the store actually kept.
const previous = { ...data };
if (Object.hasOwn(previous, field)) {
previous[field] = cloneFormValue(previous[field]);
}
setDataStore(field, value);
clearErrors(field);
const current = errors();
const affected = changedFormErrorKeys(current, previous, data);
if (affected.length > 0) {
replaceErrors(omitFormErrors(current, affected));
}
}

function reset(...args: ReadonlyArray<string | FormResetOptions>) {
Expand All @@ -107,15 +120,12 @@ export function useForm(
}

function clearErrors(...fields: ReadonlyArray<string>) {
if (fields.length === 0) {
replaceErrors({});
} else {
const next = { ...errors() };
for (const field of fields) {
delete next[field];
}
replaceErrors(next);
}
const current = errors();
replaceErrors(
fields.length === 0
? {}
: omitFormErrors(current, formErrorKeysWithin(current, fields, data)),
);
}

function setFieldError(field: string, message: string) {
Expand Down
Loading