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

125
Visualizações
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 Respostas
Responde à pergunta

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