- Create validate-handlers.js script to check for undefined event handlers - Add npm run validate:handlers command - Add prebuild hook to run validation before builds - Add ESLint no-undef rule to catch undefined references - Add documentation in scripts/README-validation.md Prevents issues like 'ReferenceError: handleSaveEditGuestbook is not defined' by validating all onClick/onChange/onSubmit handlers are defined before use. The script: - Scans all React components for event handlers - Verifies functions are defined in component scope - Excludes props and imported functions - Runs automatically before builds - Can be run manually: npm run validate:handlers
2.4 KiB
2.4 KiB
Handler Validation Script
Overview
The validate-handlers.js script checks React components to ensure all event handler functions (onClick, onChange, onSubmit, etc.) are properly defined before being used.
Why This Exists
This prevents runtime errors like ReferenceError: handleSaveEditGuestbook is not defined that occur when:
- A handler function is referenced in JSX but not defined in the component
- A function is accidentally deleted but still referenced
- A typo in function name causes undefined reference
Usage
Manual Check
npm run validate:handlers
Automatic Check
The validation runs automatically before builds via the prebuild hook in package.json.
CI/CD Integration
Add to your CI pipeline:
- name: Validate handlers
run: npm run validate:handlers
What It Checks
- Event Handlers: Finds all
onClick,onChange,onSubmithandlers - Function Definitions: Verifies functions are defined as:
const handleX = ...function handleX()const handleX = useCallback(...)const handleX = useMemo(...)
- Props: Excludes functions passed as props (handled by TypeScript)
- Imports: Excludes functions imported from other modules
Example Output
Success
🔍 Validating handler functions...
✅ All handler functions are properly defined!
Failure
🔍 Validating handler functions...
❌ src/components/features/admin/admin-dashboard.tsx
⚠️ Handler "handleSaveEditGuestbook" is referenced but not defined
❌ Validation failed: Found undefined handler functions
Adding New Handlers
When adding a new event handler:
-
Define the function first:
const handleNewAction = async () => { // implementation }; -
Then use it in JSX:
<Button onClick={handleNewAction}>Click me</Button> -
Run validation:
npm run validate:handlers
Limitations
- Cannot detect handlers in dynamically generated JSX
- May have false positives for complex prop patterns
- Does not check TypeScript types (use
npm run typecheckfor that)
Best Practices
- Always define handlers before using them
- Use TypeScript for type safety (
npm run typecheck) - Run validation before committing (
npm run validate:handlers) - Keep handlers close to where they're used (same component or nearby)