Skip to content

API Reference ‐ Form

Jerome Thayananthajothy edited this page Oct 19, 2024 · 1 revision

The main Form class provides comprehensive form state management and submission capabilities.

Constructor

constructor(initialData: TForm, axiosInstance: AxiosInstance = axios)

Creates a new form instance.

  • Parameters:
    • initialData: TForm - Initial form data
    • axiosInstance?: AxiosInstance - Optional custom Axios instance (defaults to global axios)
  • Returns: Proxied Form instance

Properties

Data Management

  • data: TForm - Current form data
  • defaults: TForm - Default form values
  • isDirty: boolean - Whether form data has been modified from defaults

Status Flags

  • processing: boolean - Whether form is currently being submitted
  • wasSuccessful: boolean - Whether last submission was successful
  • recentlySuccessful: boolean - Whether form was successfully submitted in last 2 seconds

Progress & Errors

  • progress: Progress | null - Upload progress information
    interface Progress {
      total: number;
      loaded: number;
      percentage: number;
      bytes: number;
      lengthComputable: boolean;
    }
  • errors: Partial<Record<keyof TForm | 'formError', string>> - Form validation errors

Core Methods

Form Submission

submit(method: Method, url: string, options?: Partial<FormOptions<TForm>>): Promise<void>

Submit the form with specified HTTP method.

  • Parameters:
    • method: Method - HTTP method ('get', 'post', 'put', 'patch', 'delete', 'options')
    • url: string - Submission URL
    • options?: Partial<FormOptions<TForm>> - Submission options
  • Options Interface:
    interface FormOptions<TForm> {
      onBefore?: () => void;
      onProgress?: (progress: Progress) => void;
      onSuccess?: (response: AxiosResponse) => void;
      onError?: (errors: Partial<Record<keyof TForm | 'formError', string>>) => void;
      onFinish?: () => void;
    }
HTTP Method Shortcuts
get(url: string, options?: Partial<FormOptions<TForm>>): Promise<void>
post(url: string, options?: Partial<FormOptions<TForm>>): Promise<void>
put(url: string, options?: Partial<FormOptions<TForm>>): Promise<void>
patch(url: string, options?: Partial<FormOptions<TForm>>): Promise<void>
delete(url: string, options?: Partial<FormOptions<TForm>>): Promise<void>
options(url: string, options?: Partial<FormOptions<TForm>>): Promise<void>
Debounced Submission
submitDebounced(method: Method, url: string, options?: Partial<FormOptions<TForm>>): void

Submit the form with a 300ms debounce.

Error Handling

setError(field: keyof TForm, message: string): void

Set error message for specific field.

  • Parameters:
    • field: keyof TForm - Form field name
    • message: string - Error message
setErrors(errors: Partial<Record<keyof TForm | 'formError', string>>): void

Set multiple error messages.

  • Parameters:
    • errors: Partial<Record<keyof TForm | 'formError', string>> - Object mapping fields to error messages
clearErrors(): void

Clear all form errors.

Data Management

reset(...fields: (keyof TForm)[]): void

Reset form data to defaults.

  • Parameters:
    • ...fields: (keyof TForm)[] - Optional specific fields to reset. If none provided, resets all fields.
setDefaults(fieldOrFields?: keyof TForm | Partial<TForm>, value?: FormDataConvertible): void

Set new default values.

  • Parameters:
    • fieldOrFields?: keyof TForm | Partial<TForm> - Field(s) to set as defaults
    • value?: FormDataConvertible - Value for single field
transform(callback: (data: TForm) => object): this

Transform form data before submission.

  • Parameters:
    • callback: (data: TForm) => object - Transformation function
  • Returns: Form instance for chaining

Validation

validate(): Promise<boolean>

Validate form data against defined rules.

  • Returns: Promise resolving to boolean indicating validation success

Lifecycle Management

cancel(): void

Cancel ongoing form submission.

dispose(): void

Clean up form instance and remove all data.

Types

Method Type

type Method = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'

Progress Interface

interface Progress {
  total: number;
  loaded: number;
  percentage: number;
  bytes: number;
  lengthComputable: boolean;
}

Form Options Interface

interface FormOptions<TForm> {
  onBefore?: () => void;
  onProgress?: (progress: Progress) => void;
  onSuccess?: (response: AxiosResponse) => void;
  onError?: (errors: Partial<Record<keyof TForm | 'formError', string>>) => void;
  onFinish?: () => void;
}

API Validation Error Interface

interface ApiValidationError {
  message: string;
  errors: Record<string, string[]>;
}

File Handling

The library automatically detects when form data contains files and converts the data to FormData format when necessary. File upload progress is tracked and reported through the progress property and onProgress callback.

CSRF Protection

The library automatically includes CSRF tokens from the page's meta tags:

<meta name="csrf-token" content="token-value">

Proxy Behavior

The Form class uses a Proxy to provide direct access to form fields:

  • Get operations check form data first, then instance properties
  • Set operations enforce field name validation and track dirty state
  • Reserved field names are protected from accidental overwriting

Error Handling

The library handles different types of errors:

  • HTTP 422 responses are treated as validation errors
  • Cancelled requests are not treated as errors
  • Other errors are captured in the formError field
  • All errors are available through the errors property and onError callback