Skip to main content

useFormData

A custom Preact hook for managing form state with validation support. This hook is used internally by all QR code type forms to handle input, validation, and error state.

Type Signature

function useFormData<T extends Record<string, any>>(
  options: UseFormDataOptions<T>
): UseFormDataReturn<T>

Parameters

options
UseFormDataOptions<T>
required
Configuration object for the hook.

Return Value

data
T
Current form data state.
setData
Dispatch<T>
Direct state setter for the entire form data object.
update
<K extends keyof T>(key: K, value: T[K]) => void
Update a single field in the form data. Triggers the onChange callback.
errors
Record<string, string>
Current validation errors, keyed by field name.
setErrors
Dispatch<Record<string, string>>
Direct setter for the errors object.
handleBlur
() => void
Callback to run validation when a field loses focus. Updates the errors state.
handleUpdate
<K extends keyof T>(field: K, value: T[K]) => void
Update a field and immediately validate the entire form. Combines update with validation.

Usage Example

import { useFormData } from "../../../domain/hooks/use-form-data";
import { validateUrlQr } from "../../../domain/validation/validators";
import type { UrlQrData } from "../../../domain/types/qr";

export default function UrlForm({ onChange }: { onChange?: (data: UrlQrData) => void }) {
  const { data, errors, handleUpdate } = useFormData<UrlQrData>({
    initialData: { url: "" },
    onChange,
    validate: validateUrlQr,
  });

  return (
    <input
      type="text"
      value={data.url}
      onInput={(e) => handleUpdate("url", (e.target as HTMLInputElement).value)}
    />
  );
}

Source Reference

Implemented in src/domain/hooks/use-form-data.ts:20-54.

getInputValue

Utility function to safely extract the value from HTML input events.

Type Signature

function getInputValue(e: Event): string

Parameters

e
Event
required
DOM event from an input, select, or textarea element.

Return Value

Returns the string value of the input element, or an empty string if the target is null or doesn’t have a value property.

Usage Example

import { getInputValue } from "../../../domain/hooks/use-form-data";

<input
  onInput={(e) => {
    const value = getInputValue(e);
    console.log(value); // safely extracted value
  }}
/>

Source Reference

Implemented in src/domain/hooks/use-form-data.ts:56-64.

Build docs developers (and LLMs) love