| 31 | }); |
| 32 | |
| 33 | export function EmailForm() { |
| 34 | const [isSubmitted, setIsSubmitted] = useState(false); |
| 35 | const [isLoading, setIsLoading] = useState(false); |
| 36 | const form = useForm<z.infer<typeof formSchema>>({ |
| 37 | resolver: zodResolver(formSchema), |
| 38 | defaultValues: { |
| 39 | email: "", |
| 40 | }, |
| 41 | }); |
| 42 | |
| 43 | async function onSubmit(values: z.infer<typeof formSchema>) { |
| 44 | setIsLoading(true); |
| 45 | try { |
| 46 | const response = await fetch("/api/subscribe", { |
| 47 | method: "POST", |
| 48 | headers: { |
| 49 | "Content-Type": "application/json", |
| 50 | }, |
| 51 | body: JSON.stringify({ |
| 52 | email: values.email, |
| 53 | source: source, |
| 54 | userGroup: userGroup, |
| 55 | }), |
| 56 | }); |
| 57 | |
| 58 | if (!response.ok) { |
| 59 | throw new Error("Failed to subscribe"); |
| 60 | } |
| 61 | |
| 62 | const data = await response.json(); |
| 63 | console.log("Submitted email:", values.email, "Contact ID:", data.id); |
| 64 | setIsSubmitted(true); |
| 65 | } catch (error) { |
| 66 | console.error("Error submitting email:", error); |
| 67 | form.setError("email", { |
| 68 | type: "manual", |
| 69 | message: "Failed to subscribe. Please try again.", |
| 70 | }); |
| 71 | } finally { |
| 72 | setIsLoading(false); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | return ( |
| 77 | <div> |
| 78 | {!isSubmitted ? ( |
| 79 | <Form {...form}> |
| 80 | <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-2"> |
| 81 | <FormField |
| 82 | control={form.control} |
| 83 | name="email" |
| 84 | render={({ field }) => ( |
| 85 | <FormItem> |
| 86 | <FormControl> |
| 87 | <div className="flex gap-2"> |
| 88 | <Input |
| 89 | placeholder="Your email" |
| 90 | {...field} |