I want to check on load if the object window has the property VL.refCode. I use viral loops for my website and viral loop put in window.VL object the property refCode when a user is registered.
I put a for loop in a useEffect to check if this property exists or not, but unfortunately it becomes an infinite loop.
useEffect(() => {
if(window.VL){
if(window.VL.refCode){
setCryptoButtonMessage(t('common:cryptoButton_already_register'))
console.log('useEffect :user already register')
}
else{
console.log('useEffect : window.vl.refcode not exist')
}
}
else {
setCryptoButtonMessage(t('common:cryptoButton_title_waitlist'))
}
// t is for translation with i18n
},[t]);
This solution doesn't work because viral loop create window.VL object 1 to 2sec max after the first render. If I put a setTimeout it's not a valid solution for users with mobile device / slow 3g / without fiber
So i use this solution
useEffect(() => {
let animation;
const check = () => {
console.log('je suis dans check');
console.log('je suis dans for');
if ((Object.prototype.hasOwnProperty.call(window.VL, 'refCode'))) {
console.log('je trouve refCode ');
setCryptoButtonMessage(t('common:cryptoButton_already_register'))
cancelAnimationFrame(animation);
return;
}
animation = requestAnimationFrame(check);
};
animation = requestAnimationFrame(check);
},[t]);
But this solution will never stop until window.VL.refCode exist ... not really best solution for website performance ...
I try to put a " simulate timer " but it becomes an infinite loop ...
useEffect(() => {
for (let i = 1; i < 10000; i += 1) {
let animation;
const check = () => {
if ((Object.prototype.hasOwnProperty.call(window.VL, 'refCode'))) {
setCryptoButtonMessage(t('common:cryptoButton_already_register'))
cancelAnimationFrame(animation);
return;
}
animation = requestAnimationFrame(check);
};
animation = requestAnimationFrame(check);
}
},[t]);
I don't know of any way of being automatically told when an object gets created on the window - so as far as I know the only way to do this is with a poll. If it was me, I'd abstract the logic for polling for the ref code into a new hook:
import { useEffect, useRef, useState } from 'react';
const useRefCode = (pollTimeMillis = 1000) => {
const timeoutRef = useRef(undefined);
const [refCode, setRefCode] = useState(window.VL?.refCode);
const cancelTimeout = () => {
if (!timeoutRef.current) return;
clearTimeout(timeoutRef.current);
timeoutRef.current = undefined;
};
useEffect(() => {
if (refCode) return;
setTimeout(() =>
setRefCode(window.VL?.refCode || undefined),
pollTimeMillis
);
return cancelTimeout;
}, [refCode]);
return refCode;
}
Then your other component that wants to change the message based on the ref code becomes very simple:
const OtherComponent = () => {
const refCode = useRefCode();
const translationKey = refCode
? 'common:cryptoButton_already_register'
: 'common:cryptoButton_title_waitlist';
return (
<div>{t(translationKey)}</div>
);
}