Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Infinite for loop en useEffect cuando quiero verificar si una propiedad del objeto de ventana está aquí

Quiero verificar al cargar si la ventana del objeto tiene la propiedad VL.refCode. Utilizo bucles virales para mi sitio web y pongo el bucle viral en window.VL objeta la propiedad refCode cuando un usuario está registrado.

Puse un bucle for en un useEffect para verificar si esta propiedad existe o no, pero desafortunadamente se convierte en un bucle infinito.

 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]);

Esta solución no funciona porque el bucle viral crea el objeto window.VL de 1 a 2 segundos como máximo después del primer procesamiento. Si pongo un setTimeout no es una solución válida para usuarios con dispositivo móvil/3g lento/sin fibra

Así que uso esta solución

 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]);

Pero esta solución nunca se detendrá hasta que exista window.VL.refCode ... no es realmente la mejor solución para el rendimiento del sitio web ...

Intento poner un "temporizador de simulación" pero se convierte en un bucle infinito...

 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 answers
Answer question

0

No conozco ninguna forma de que me digan automáticamente cuándo se crea un objeto en la ventana; por lo que sé, la única forma de hacerlo es con una encuesta. Si fuera yo, abstraería la lógica para sondear el código de referencia en un nuevo gancho:

 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; }

Luego, su otro componente que quiere cambiar el mensaje en función del código de referencia se vuelve muy 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!