Analytics Events
Form Guardian provides comprehensive analytics events for tracking form interactions and draft lifecycle.
Overview
Analytics events allow you to:
- Track when drafts are saved or restored
- Monitor draft expiration
- Integrate with analytics systems (Google Analytics, Mixpanel, etc.)
- Show custom UI feedback
- Implement confirmation dialogs before restore
Available Events
onBeforeSave
Called before a draft is saved to storage. Use this to:
- Track save attempts
- Validate data before saving
- Show loading indicators
import { useFormAutosave } from '@form-guardian/react';
const { formRef } = useFormAutosave('my-form', {
onBeforeSave: async (values) => {
console.log('About to save:', values);
// Track in analytics
analytics.track('draft_save_start', { formId: 'my-form' });
// Show loading indicator
setSaving(true);
},
});
onAfterSave
Called after a draft is successfully saved. Use this to:
- Track successful saves
- Update UI state
- Show success notifications
const { formRef } = useFormAutosave('my-form', {
onAfterSave: async (values) => {
console.log('Saved successfully:', values);
// Track in analytics
analytics.track('draft_save_success', { formId: 'my-form' });
// Update UI
setSaving(false);
showNotification('Draft saved');
},
});
onBeforeRestore
Called before a draft is restored to the form. Use this to:
- Show confirmation dialogs
- Track restore attempts
- Validate restored data
const { formRef } = useFormAutosave('my-form', {
onBeforeRestore: async (values) => {
console.log('About to restore:', values);
// Show confirmation dialog
const confirmed = await showConfirmDialog('Restore draft?');
if (!confirmed) {
throw new Error('Restore cancelled');
}
// Track in analytics
analytics.track('draft_restore_start', { formId: 'my-form' });
},
});
Note: If onBeforeRestore throws an error, the restore will be cancelled.
onAfterRestore
Called after a draft is successfully restored. Use this to:
- Track successful restores
- Show restore notifications
- Update UI state
const { formRef } = useFormAutosave('my-form', {
onAfterRestore: async (values) => {
console.log('Restored successfully:', values);
// Track in analytics
analytics.track('draft_restore_success', { formId: 'my-form' });
// Show notification
showNotification('Draft restored');
},
});
onDraftExpired
Called when a draft expires due to TTL. Use this to:
- Track expiration events
- Show expiration notifications
- Clean up related data
const { formRef } = useFormAutosave('my-form', {
ttl: { days: 7 },
onDraftExpired: async (draftId) => {
console.log('Draft expired:', draftId);
// Track in analytics
analytics.track('draft_expired', { draftId });
// Show notification
showNotification('Your draft has expired');
},
});
Usage with Vanilla JavaScript
import { attachFormAutosave } from '@form-guardian/dom';
const autosave = attachFormAutosave({
formId: 'my-form',
root: formElement,
onBeforeSave: async (values) => {
console.log('About to save:', values);
analytics.track('draft_save_start');
},
onAfterSave: async (values) => {
console.log('Saved successfully:', values);
analytics.track('draft_save_success');
},
onBeforeRestore: async (values) => {
const confirmed = confirm('Restore draft?');
if (!confirmed) {
throw new Error('Restore cancelled');
}
},
onAfterRestore: async (values) => {
console.log('Restored successfully:', values);
showNotification('Draft restored');
},
onDraftExpired: async (draftId) => {
console.log('Draft expired:', draftId);
showNotification('Your draft has expired');
},
});
Integration Examples
Google Analytics
const { formRef } = useFormAutosave('checkout-form', {
onAfterSave: async (values) => {
// Google Analytics 4
gtag('event', 'draft_saved', {
form_id: 'checkout-form',
form_type: 'checkout',
});
},
onAfterRestore: async (values) => {
gtag('event', 'draft_restored', {
form_id: 'checkout-form',
});
},
});
Mixpanel
const { formRef } = useFormAutosave('contact-form', {
onAfterSave: async (values) => {
mixpanel.track('Draft Saved', {
formId: 'contact-form',
fieldCount: Object.keys(values).length,
});
},
});
Custom Analytics Service
const { formRef } = useFormAutosave('my-form', {
onBeforeSave: async (values) => {
await customAnalytics.logEvent({
type: 'draft_save_start',
formId: 'my-form',
timestamp: Date.now(),
});
},
onAfterSave: async (values) => {
await customAnalytics.logEvent({
type: 'draft_save_success',
formId: 'my-form',
fieldCount: Object.keys(values).length,
timestamp: Date.now(),
});
},
});
Best Practices
-
Handle errors gracefully - Analytics should never break your form
onAfterSave: async (values) => {
try {
await analytics.track('draft_saved', { formId: 'my-form' });
} catch (error) {
console.error('Analytics error:', error);
// Don't throw - let the form continue working
}
} -
Use async/await - All event handlers support async operations
onBeforeRestore: async (values) => {
// This will wait for confirmation before restoring
const confirmed = await showConfirmDialog('Restore draft?');
if (!confirmed) {
throw new Error('Restore cancelled');
}
} -
Track meaningful data - Include relevant context in analytics
onAfterSave: async (values) => {
analytics.track('draft_saved', {
formId: 'my-form',
fieldCount: Object.keys(values).length,
hasEmail: !!values.email,
timestamp: Date.now(),
});
}
Next Steps
- 📖 API Reference - Complete API documentation
- 📈 Draft Status Hook - Track draft status in real-time
- ✅ Best Practices - Tips and common pitfalls