Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
Infinite for loop in useEffect when i want to check if a property of window object is here

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]);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
    );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda