import { useState, useRef } from "react"; import axios from "axios"; import CheckIcon from "../../icons/CheckIcon"; import Turnstile from "./Turnstile"; import { useNavigate } from "react-router-dom"; import { useContent } from "../../contexts/ContentContext"; import LoadingIcon from "../../icons/LoadingIcon.jsx"; import { useEffect } from "react"; const apiUrl = import.meta.env.VITE_API_URL; const turnstileKey = import.meta.env.VITE_TURNSTILE_KEY; const ContactForm = () => { const navigate = useNavigate(); const { settings } = useContent(); const turnstileRef = useRef(null); // Ref for Turnstile const [formData, setFormData] = useState({ name: "", email: "", message: "", }); const [token, setToken] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [loadTurnstile, setLoadTurnstile] = useState(false); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value, }); }; useEffect(() => { if (turnstileKey && turnstileKey != "") { setTimeout(() => { setLoadTurnstile(true); }, 500); } }, []); const handleSubmit = async (e) => { e.preventDefault(); if (!token) { alert("Please complete the CAPTCHA"); return; } try { setLoading(true); // Send formData + token to your backend using axios const response = await axios.post(`${apiUrl}/contact`, { ...formData, token, }); console.log(settings); navigate(`/${settings.redirects.contactFormComplete}`); console.log("Form submitted:", response.data); } catch (error) { console.error("Error submitting form:", error); const errorData = error.response.data; setError(errorData); if (errorData.code.startsWith("captcha-")) { turnstileRef.current.reset(); } } finally { setLoading(false); } }; return (
{/* Cloudflare Turnstile */} {loadTurnstile == true && ( setToken(token)} /> )}
{error &&

{error.message}

}
); }; export default ContactForm;