Tracking recipes

Form tracking

Call one function after each submission to record whether it worked.

hooks/use-form-tracking.ts
import { track } from "@databuddy/sdk";
import { useCallback } from "react";

export function useFormTracking(formName: string) {
  return useCallback(
    (success: boolean, errors: Record<string, string[]> = {}) => {
      const errorCount = Object.keys(errors).length;
      track("form_submit", {
        form_name: formName,
        success,
        error_count: errorCount,
        has_errors: errorCount > 0,
      });
    },
    [formName]
  );
}
components/contact-form.tsx
export function ContactForm() {
  const trackSubmit = useFormTracking("contact");

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    try {
      await sendMessage(new FormData(event.currentTarget));
      trackSubmit(true);
    } catch {
      trackSubmit(false, { general: ["Couldn't send"] });
    }
  }

  return <form onSubmit={handleSubmit}>{/* fields */}</form>;
}

What it sends

EventPropertyValue
form_submitform_nameThe name you pass, such as contact
successWhether the submission worked
error_countHow many fields had errors
has_errorserror_count > 0

Track failed submissions too, so you can compare completion and error rates. With autocapture.interactions on, the tracker also reports the last field touched in abandoned forms.

How is this guide?