Blog>
Snippets

Debugging and Troubleshooting Forms

Offer tips and techniques for debugging complex form issues in Solid.js applications using TanStack Form, including common pitfalls and their solutions.
import { useForm } from '@tanstack/react-form';

// Initialize your form with useForm
const form = useForm({
  defaultValues: { name: '', email: '' },
  onSubmit: async (values) => { console.log(values); }
});
This snippet initializes a form using TanStack's useForm hook, specifying default values and an onSubmit function to log form values.
import { useEffect } from 'solid-js';

// Log form state changes
effect(() => {
  console.log('Form state changed:', form.values);
});
Utilizes Solid.js's useEffect (renamed as 'effect' in Solid) to log form state changes, helping in debugging state-related issues by observing real-time form values.
form.setError('name', 'required', 'Name is required');

// Check for specific field error
if (form.getFieldState('name').error === 'required') {
  console.error('Name field is required.');
}
Sets a manual error on the 'name' field and checks for this specific error, exemplifying how to manually manage field errors and validate form inputs.
form.validate().then(errors => {
  if (errors.length > 0) {
    console.error('Validation errors:', errors);
  }
});
Performs asynchronous validation of the entire form and logs any validation errors, facilitating the identification and debugging of validation rules.