Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hotfix/test mailchimp worker #59

Merged
merged 2 commits into from
Jan 27, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 35 additions & 102 deletions src/components/Newsletter/Newsletter.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ const Newsletter = () => {
const [captchaError, setCaptchaError] = useState("");
const [token, setToken] = useState(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isFocused, setIsFocused] = useState(false);
const reCaptchaRef = useRef(null);
const timeoutRef = useRef(null);

const siteKey = process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY;

const handleChange = (e) => {
setEmail(e.target.value);
// Reset status messages when user starts typing again
setStatus(null);
setMsg("");
setCaptchaError("");
Expand All @@ -29,127 +28,57 @@ const Newsletter = () => {
setCaptchaError("");
};

const cleanup = (callbackName, scriptId) => {
// Clear timeout if it exists
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}

// Remove callback function
if (window[callbackName]) {
delete window[callbackName];
}

// Remove script tag
const scriptElement = document.getElementById(scriptId);
if (scriptElement) {
document.body.removeChild(scriptElement);
}

setIsSubmitting(false);
};
const handleFocus = () => setIsFocused(true);
const handleBlur = () => setIsFocused(false);

const handleSubmit = async (e) => {
e.preventDefault();
console.log("Form submitted", { email, token, isSubmitting }); // Debug log

// Prevent multiple submissions
if (isSubmitting) {
console.log("Already submitting");
return;
}

// Validate email
if (isSubmitting) return;
if (!email) {
console.log("No email provided");
setStatus("Error");
setMsg("Please enter your email address.");
return;
}

// Verify reCAPTCHA
if (!token) {
console.log("No reCAPTCHA token");
setCaptchaError("Please complete the reCAPTCHA challenge!");
// Reset reCAPTCHA to ensure it's fresh
reCaptchaRef.current?.reset();
return;
}

try {
setIsSubmitting(true);
console.log("Starting submission process"); // Debug log

// Create unique IDs for this submission
const timestamp = Date.now();
const callbackName = `jsonpCallback_${timestamp}`;
const scriptId = `mailchimpScript_${timestamp}`;

// Set timeout for the request (10 seconds)
timeoutRef.current = setTimeout(() => {
console.log("Request timed out"); // Debug log
cleanup(callbackName, scriptId);
setStatus("Error");
setMsg("Request timed out. Please try again.");
}, 10000);

// Define the callback function
window[callbackName] = (response) => {
console.log("Mailchimp response:", response); // Debug log

// Handle Mailchimp's specific response format
if (response.result === "success") {
setStatus("Success");
setMsg("Thank you for subscribing!");
reCaptchaRef.current?.reset();
setToken(null);
setEmail(""); // Clear email on success
} else if (response.msg && response.msg.toLowerCase().includes("already subscribed")) {
setStatus("Success");
setMsg("You're already subscribed to our newsletter!");
reCaptchaRef.current?.reset();
setToken(null);
} else {
setStatus("Error");
// Handle Mailchimp's error messages more gracefully
const errorMsg = response.msg || "An error occurred. Please try again.";
setMsg(errorMsg.replace(/<(?:.|\n)*?>/gm, "")); // Strip HTML from error message
}
cleanup(callbackName, scriptId);
};

// Create and append the script element
const script = document.createElement("script");
script.id = scriptId;
script.onerror = () => {
console.log("Script loading error"); // Debug log
cleanup(callbackName, scriptId);
setStatus("Error");
setMsg("Failed to connect to the subscription service. Please try again.");
};

// Construct Mailchimp URL with all required parameters
const params = new URLSearchParams({
u: "cde2461ba84f5279fff352829",
id: "8d165e36d3",
EMAIL: email,
"group[57543][1]": "1",
c: callbackName,
"g-recaptcha-response": token,
b_cde2461ba84f5279fff352829_8d165e36d3: "",
const response = await fetch("https://eff999e9-celestia-newsletter-worker.infra-admin-749.workers.dev/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email,
recaptchaToken: token,
}),
});

const url = `https://us6.list-manage.com/subscribe/post-json?${params.toString()}`;
console.log("Request URL:", url); // Debug log
const data = await response.json();

script.src = url;
document.body.appendChild(script);
if (data.success) {
setStatus("Success");
setMsg("Thank you for subscribing!");
setEmail("");
} else {
setStatus("Error");
setMsg(
data.error === "Already subscribed"
? "You're already subscribed to our newsletter!"
: data.error || "An error occurred. Please try again."
);
}
} catch (error) {
console.error("Submission error:", error); // Debug log
cleanup(callbackName, scriptId);
setStatus("Error");
setMsg("An unexpected error occurred. Please try again.");
} finally {
setIsSubmitting(false);
reCaptchaRef.current?.reset();
setToken(null);
}
};

Expand All @@ -160,9 +89,11 @@ const Newsletter = () => {
<div className={"w-full relative"}>
<label
htmlFor={"email"}
className={`px-2 py-3 absolute text-sm leading-[1.2857] transition-all ${
email.length > 0 ? "-top-8 -left-2 text-opacity-100" : "top-0 left-0 text-opacity-60 pointer-events-none"
}`}
className={`absolute text-sm leading-[1.2857] transition-all duration-200 ${
email.length > 0 || isFocused
? "-translate-y-6 text-opacity-100 text-xs"
: "translate-y-3 text-opacity-60 pointer-events-none"
} px-2`}
>
Email
</label>
Expand All @@ -174,6 +105,8 @@ const Newsletter = () => {
captchaError ? "border-red-error-subtle" : "border-white"
}`}
onChange={handleChange}
onFocus={handleFocus}
onBlur={handleBlur}
required
disabled={isSubmitting}
/>
Expand Down
Loading