Form Submission

Learn how to handle form submissions with proper state management, error handling, and user feedback.

Basic Form Submission

export class ContactForm {
  formData = {
    name: '',
    email: '',
    message: ''
  };

  isSubmitting = false;
  successMessage = '';
  errorMessage = '';

  async handleSubmit() {
    this.isSubmitting = true;
    this.errorMessage = '';
    this.successMessage = '';

    try {
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(this.formData)
      });

      if (!response.ok) {
        throw new Error('Submission failed');
      }

      this.successMessage = 'Form submitted successfully!';
      this.resetForm();
    } catch (error) {
      this.errorMessage = 'Failed to submit form. Please try again.';
    } finally {
      this.isSubmitting = false;
    }
  }

  resetForm() {
    this.formData = { name: '', email: '', message: '' };
  }
}

Preventing Default Submission

Validation Before Submission

Submission State Management

Optimistic UI Updates

Debounced Auto-Save

Rate Limiting

Multi-Step Forms

See the Template Recipes collection for complete examples, including community-contributed multi-step flows.

Best Practices

  1. Always provide feedback - Show loading, success, and error states

  2. Disable submit button - Prevent multiple submissions

  3. Handle errors gracefully - Show user-friendly error messages

  4. Validate before submitting - Client-side validation for UX

  5. Reset form after success - Clear form or redirect user

  6. Implement rate limiting - Prevent spam submissions

  7. Use proper HTTP methods - POST for creation, PUT/PATCH for updates

Common Patterns

Submit on Enter Key

Confirm Before Submit

Redirect After Success

Last updated

Was this helpful?