-
-
Notifications
You must be signed in to change notification settings - Fork 2
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.
- Core Concepts
- Installation
- Basic Usage
- Form Instance
- Submission Methods
- Error Handling
- File Uploads
- TypeScript Integration
The Form Library is built around three main concepts:
- Type Safety: Everything is fully typed with TypeScript
- State Management: Automatic tracking of form state
- Event Lifecycle: Comprehensive hooks for form events
- 🔒 Full TypeScript support
- 📦 Built-in CSRF handling
- 🔄 Progress tracking
- 🎯 Validation error management
- 🔌 Rich event hooks
- ⚡ Proxy-based field access
- 📱 Framework agnostic
- 🚀 File upload support
npm install formlink
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');
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 |
// 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()
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');
}
});
// 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');
interface FormOptions<TForm> {
onBefore?: () => void;
onProgress?: (progress: Progress) => void;
onSuccess?: (response: AxiosResponse) => void;
onError?: (errors: Record<keyof TForm | 'formError', string>) => void;
onFinish?: () => void;
}
// Single error
form.setError('email', 'Invalid email format');
// Multiple errors
form.setErrors({
email: 'Invalid email',
name: 'Name is required'
});
// Clear errors
form.clearErrors();
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."]
}
}
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`);
}
});
interface Progress {
total: number;
loaded: number;
percentage: number;
bytes: number;
lengthComputable: boolean;
}
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
The library provides full type inference for:
- Form fields
- Error keys
- Transformation functions
- Event callbacks
-
Type Definition
// Define interfaces for your forms interface LoginForm { email: string; password: string; remember: boolean; }
-
Error Handling
// Always handle errors appropriately await form.post('/api/login', { onError: (errors) => { if (errors.email) { // Handle email errors } } });
-
Progress Tracking
// Track progress for file uploads form.post('/api/upload', { onProgress: (progress) => { updateProgressBar(progress.percentage); } });
-
Resource Cleanup
// Clean up when form is no longer needed onUnmount(() => { form.dispose(); });
import axios from 'axios';
const customAxios = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
});
const form = new Form(data, customAxios);
form.transform((data) => ({
...data,
name: data.name.trim(),
email: data.email.toLowerCase()
}));
// Submits after 300ms of inactivity
form.submitDebounced('post', '/api/search');