Skip to content

Commit 891a6bc

Browse files
authored
Fix turnstile tokens being invalid if waiting too long (#296)
1 parent 911b7dd commit 891a6bc

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

src/components/store/StoreItem.tsx

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import ErrorPopup, { useErrorPopup } from '../ErrorPopup';
1515
import ReactNavbar from '../generic/ReactNavbar';
1616
import { LoadingSpinner } from '../generic/LargeLoadingSpinner';
1717
import AuthActionButton, { type ShowErrorFunction } from '../AuthActionButton';
18-
import { Turnstile } from '@marsidev/react-turnstile';
18+
import { Turnstile, type TurnstileInstance } from '@marsidev/react-turnstile';
1919
import type {
2020
IPublicClientApplication,
2121
AccountInfo,
@@ -91,6 +91,7 @@ const StoreItem = ({
9191
const activeMembershipKeyRef = useRef<string | null>(null);
9292
const membershipCache = useRef<Map<string, boolean>>(new Map());
9393

94+
const turnstileRef = useRef<TurnstileInstance>(null);
9495
const { error, showError, clearError } = useErrorPopup();
9596

9697
const turnstileSiteKey = import.meta.env.PUBLIC_TURNSTILE_SITE_KEY!;
@@ -107,6 +108,13 @@ const StoreItem = ({
107108
.catch(console.error);
108109
}, []);
109110

111+
// If there is only one variant, select it by default.
112+
useEffect(() => {
113+
if (!selectedVariantId && productInfo?.variants.length === 1) {
114+
setSelectedVariantId(productInfo.variants[0].variantId ?? '');
115+
}
116+
}, [productInfo]);
117+
110118
// Check membership status with specific lists (with caching)
111119
const checkMembershipStatus = useCallback(
112120
async (lists: string[] | null) => {
@@ -935,11 +943,18 @@ const StoreItem = ({
935943

936944
<div className="w-full">
937945
<Turnstile
946+
ref={turnstileRef}
938947
id={id}
939948
siteKey={turnstileSiteKey}
940949
onSuccess={setTurnstileToken}
941-
onExpire={() => setTurnstileToken(undefined)}
942-
onError={() => setTurnstileToken(undefined)}
950+
onExpire={() => {
951+
setTurnstileToken(undefined);
952+
turnstileRef.current?.reset();
953+
}}
954+
onError={() => {
955+
setTurnstileToken(undefined);
956+
turnstileRef.current?.reset();
957+
}}
943958
options={{
944959
size: 'flexible',
945960
theme: 'light',

0 commit comments

Comments
 (0)