Loading page
Read FormData on submit, validate once for feedback, post JSON, render a status message.
import { useState } from "react";
export function ContactForm() {
const [state, setState] = useState<"idle" | "sending" | "sent" | "error">("idle");
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = event.currentTarget;
const payload = Object.fromEntries(new FormData(form));
setState("sending");
const response = await fetch("https://formivo.faizyab.me/api/f/YOUR_FORM_ID", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify(payload),
}).catch(() => null);
if (!response?.ok) {
setState("error");
return;
}
form.reset();
setState("sent");
}
return (
<form onSubmit={onSubmit}>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" required />
<button disabled={state === "sending"}>
{state === "sending" ? "Sending…" : "Send"}
</button>
{state === "sent" && <p role="status">Thanks — we will reply shortly.</p>}
{state === "error" && <p role="alert">Could not send. Please try again.</p>}
</form>
);
}201 on success. Treat any non-2xx as a failure and keep the entered values.
| Symptom | Fix |
|---|---|
| Values disappear | You reset the form before the request finished. |
| Stale event in React 17+ | Use event.currentTarget, captured before the first await. |