personal-site/functions/frontend/submitContactForm.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-10-24 17:59:00 +00:00
import { Dispatch, SetStateAction } from "react";
2024-01-30 03:27:23 +00:00
export default async function submitContactForm(
e: any,
setSuccess: Dispatch<SetStateAction<string | null>>,
setLoading: Dispatch<SetStateAction<boolean>>
) {
2023-10-24 17:59:00 +00:00
e.preventDefault();
setLoading(true);
let name = e.target[0].value;
let email = e.target[1].value;
let message = e.target[2].value;
let body = {
name: name,
email: email,
message: message,
};
2024-01-30 03:27:23 +00:00
try {
let res = await fetch("/api/contactForm", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
let data = await res.json();
console.log(data);
if (data.msg === "Success") {
setSuccess("Success");
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
setSuccess("Failed");
}
setLoading(false);
2024-01-30 03:29:07 +00:00
} catch (error: any) {
console.log(
"Form submission failed. Please try again in a minute.",
error.message
);
window.alert("Form submission failed. Please try again in a minute.");
2023-10-24 17:59:00 +00:00
}
}