VergeStackVergeStack

Forms

The useAction hook provides a convenient way to handle form submissions in React applications. It offers built-in form handling capabilities, error management, and progressive enhancement support.

Basic Form Handling

To use useAction with forms, spread the handlers object onto your form element:

import { useAction } from '@vergestack/api-react';
import { greetingAction } from './actions';
 
export function GreetingComponent() {
  const { data, errors, handlers } = useAction(greetingAction);
 
  return (
    <>
      <form {...handlers}>
        <input name="username" />
        <button type="submit">Greet</button>
      </form>
 
      {data && <p>Data: {data}</p>}
      {errors && <p>Errors: {errors.join(', ')}</p>}
    </>
  );
}

The handlers object contains all the necessary event handlers and attributes for the form to work with both JavaScript enabled and disabled (progressive enhancement). When JavaScript is enabled, the form submission will be handled client-side with enhanced features. When JavaScript is disabled, the form will fall back to native browser form submission behavior.

Progressive Enhancement

Forms using the {...handlers} syntax work without JavaScript enabled. This ensures your application remains functional even if JavaScript fails to load or is disabled.

Form Error Handling

The getFormError function is used to retrieve form-specific errors. The function accepts a field name and returns the first error message for that field if one exists.

import { useAction } from '@vergestack/api-react';
import { greetingAction } from './actions';
 
export function GreetingComponent() {
  const { handlers, getFormError } = useAction(greetingAction);
 
  return (
    <>
      <form {...handlers}>
        <input name="name" />
        <p className="text-red-500">
          {getFormError('name')}
        </p>
        <button type="submit">Greet</button>
      </form>
    </>
  );
}

Note

Registering a getFormError handler will mark those errors as handled. It's recommended to use getFormError for inline field validation feedback and an onError handler for general error messages. To avoid duplicate errors, you can check the isReasonRegistered property in your onError handler.

For more advanced usage and the full API reference, check out the API Reference page.

On this page