Skip to content

Commit

Permalink
turnstile infinite rendering loop fix
Browse files Browse the repository at this point in the history
  • Loading branch information
cankurttekin committed Nov 12, 2024
1 parent 4cf7cde commit df7ee5b
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions frontend/src/components/Turnstile.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ 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);
};

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;
Expand All @@ -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]);
Expand Down

0 comments on commit df7ee5b

Please sign in to comment.