Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
How to wait for state to not be undefiened in ReactJS?

With this code on the component mount, there is a bug where priceToDisplay is first set as undefined, and it won't change state until some part of the component is not rerendered. If I remove that const from the dependencie array in useEffect, the correct value will be set.

 const [isOnDiscount, setIsOnDiscount] = useState(
        parseInt(product_data.discount_price && product_data.discount_price) !== 0
      );
      const [priceToDisplay, setPriceToDisplay] = useState(
        isOnDiscount ? product_data.discount_price : product_data.price_of_product
      );

  useEffect(() => {
    const isOnDiscountEffect = parseInt(product_data.discount_price) !== 0;
    const priceToDisplayEffect = 0;
    console.log(priceToDisplay);

    if (isOnDiscountEffect) {
      setPriceToDisplay(product_data.discount_price);
    } else if (doesVariationAffectPrice()) {
      // price of variation
    } else {
      setPriceToDisplay(product_data.price_of_product);
    }
  }, [priceToDisplay]);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Difficult to tell without knowing the whole component, but I assume that you are trying to do something like this:

export const Simple = ({product_data}) => {

  const [priceToDisplay, setPriceToDisplay] = useState(null);

  const isOnDiscount = parseInt(product_data.discount_price) !== 0;


  useEffect(() => {

    if (isOnDiscount) {
      setPriceToDisplay(product_data.discount_price);
    } else if (doesVariationAffectPrice()) {
      // price of variation
    } else {
      setPriceToDisplay(product_data.price_of_product);
    }
  }, [isOnDiscount]);

  return <div>
    {priceToDisplay}
  </div>

};

you dont need a state variable for isOnDiscountfor that.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda