Skip to content

Overview

Jerome Thayananthajothy edited this page Oct 19, 2024 · 2 revisions

Welcome to the Form Library API documentation. This library provides a robust, type-safe solution for handling forms in TypeScript applications.

Table of Contents

Core Concepts

The Form Library is built around three main concepts:

  1. Type Safety: Everything is fully typed with TypeScript
  2. State Management: Automatic tracking of form state
  3. Event Lifecycle: Comprehensive hooks for form events

Key Features

  • 🔒 Full TypeScript support
  • 📦 Built-in CSRF handling
  • 🔄 Progress tracking
  • 🎯 Validation error management
  • 🔌 Rich event hooks
  • ⚡ Proxy-based field access
  • 📱 Framework agnostic
  • 🚀 File upload support

Installation

npm install formlink

Basic Usage

import { Form } from 'formlink';

// Define your form structure
interface UserForm {
  name: string;
  email: string;
}

// Create a form instance
const form = new Form<UserForm>({
  name: '',
  email: ''
});

// Submit the form
await form.post('/api/users');

Form Instance

Properties

Property Type Description
data TForm Current form data
errors Record<string, string> Validation errors
processing boolean Submission status
progress Progress | null Upload progress
isDirty boolean Modified status
wasSuccessful boolean Success status
recentlySuccessful boolean Recent success status

Methods Overview

// Form submission
form.submit(method, url, options?)
form.get(url, options?)
form.post(url, options?)
form.put(url, options?)
form.patch(url, options?)
form.delete(url, options?)

// Error handling
form.setError(field, message)
form.setErrors(errors)
form.clearErrors()

// Data management
form.reset(...fields?)
form.setDefaults(fields?)
form.transform(callback)

// Lifecycle
form.cancel()
form.dispose()

Submission Methods

Standard Submit

await form.submit('post', '/api/users', {
  onBefore: () => {
    console.log('Starting submission...');
  },
  onSuccess: (response) => {
    console.log('Success!', response.data);
  },
  onError: (errors) => {
    console.error('Validation failed:', errors);
  },
  onFinish: () => {
    console.log('Submission complete');
  }
});

Method Shortcuts

// GET request
await form.get('/api/users');

// POST request
await form.post('/api/users');

// PUT request
await form.put('/api/users/1');

// PATCH request
await form.patch('/api/users/1');

// DELETE request
await form.delete('/api/users/1');

Options Interface

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

Error Handling

Setting Errors

// Single error
form.setError('email', 'Invalid email format');

// Multiple errors
form.setErrors({
  email: 'Invalid email',
  name: 'Name is required'
});

// Clear errors
form.clearErrors();

Validation Errors

The library automatically handles Laravel-style validation responses:

// HTTP 422 response
{
  message: "The given data was invalid.",
  errors: {
    email: ["The email must be a valid email address."],
    name: ["The name field is required."]
  }
}

File Uploads

Handling Files

interface UploadForm {
  file: File;
  description: string;
}

const form = new Form<UploadForm>({
  file: null,
  description: ''
});

// Track upload progress
await form.post('/api/upload', {
  onProgress: (progress) => {
    console.log(`${progress.percentage}% uploaded`);
  }
});

Progress Interface

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

TypeScript Integration

Type Safety

interface UserForm {
  name: string;
  email: string;
  preferences: {
    newsletter: boolean;
    theme: 'light' | 'dark';
  };
}

const form = new Form<UserForm>({
  name: '',
  email: '',
  preferences: {
    newsletter: false,
    theme: 'light'
  }
});

// TypeScript enforces type safety
form.name = 'John'; // ✅ Valid
form.email = true;  // ❌ Type error

Type Inference

The library provides full type inference for:

  • Form fields
  • Error keys
  • Transformation functions
  • Event callbacks

Best Practices

  1. Type Definition

    // Define interfaces for your forms
    interface LoginForm {
      email: string;
      password: string;
      remember: boolean;
    }
  2. Error Handling

    // Always handle errors appropriately
    await form.post('/api/login', {
      onError: (errors) => {
        if (errors.email) {
          // Handle email errors
        }
      }
    });
  3. Progress Tracking

    // Track progress for file uploads
    form.post('/api/upload', {
      onProgress: (progress) => {
        updateProgressBar(progress.percentage);
      }
    });
  4. Resource Cleanup

    // Clean up when form is no longer needed
    onUnmount(() => {
      form.dispose();
    });

Advanced Usage

Custom Axios Instance

import axios from 'axios';

const customAxios = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000
});

const form = new Form(data, customAxios);

Data Transformation

form.transform((data) => ({
  ...data,
  name: data.name.trim(),
  email: data.email.toLowerCase()
}));

Debounced Submission

// Submits after 300ms of inactivity
form.submitDebounced('post', '/api/search');