diff --git a/frontend/src/components/Turnstile.js b/frontend/src/components/Turnstile.js index c28c94cd..3a4de074 100644 --- a/frontend/src/components/Turnstile.js +++ b/frontend/src/components/Turnstile.js @@ -3,9 +3,10 @@ import React, { useEffect, useRef, useState } from 'react'; const Turnstile = ({ siteKey, onVerify }) => { const [captchaLoaded, setCaptchaLoaded] = useState(false); const captchaRef = useRef(null); + const turnstileRendered = useRef(false); // Ref to track if Turnstile is already rendered useEffect(() => { - // Ensure the script is loaded and Turnstile is initialized + // Load the Turnstile script if not already loaded const handleLoad = () => { setCaptchaLoaded(true); }; @@ -13,7 +14,6 @@ const Turnstile = ({ siteKey, onVerify }) => { if (window.turnstile && window.turnstile.render) { handleLoad(); } else { - // Check if the script is loaded const script = document.createElement('script'); script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js'; script.async = true; @@ -23,18 +23,19 @@ const Turnstile = ({ siteKey, onVerify }) => { } return () => { - // Cleanup: we don't need to handle removal of the script as it's loaded only once globally + // Cleanup: No need to remove the script as it should be loaded only once }; }, []); useEffect(() => { - if (captchaLoaded && siteKey) { - // Render the Turnstile widget after the script has loaded + if (captchaLoaded && siteKey && !turnstileRendered.current) { + // Render the Turnstile widget only if it hasn't been rendered already if (captchaRef.current) { window.turnstile.render(captchaRef.current, { sitekey: siteKey, - callback: onVerify, // callback when captcha is successfully verified + callback: onVerify, }); + turnstileRendered.current = true; // Mark as rendered } } }, [captchaLoaded, siteKey, onVerify]);