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

200
Visualizações
Using an if statement for detecting whether value is returning undefined not working

I'm making an app using React-Use-Cart. I am using the getItem hook to detect changes in the price. Its really simple, and this is how this works: if the item has a quantity more than 0, then it will return the price or if it's 0, then it will return undefined.

So, here is my program -

const totalitem = getItem(products.id).itemTotal;
const totalitem2 = JSON.stringify(totalitem);

and

<h1>{totalitem === "undefined" ? "Zero!" : totalitem2}</h1>

This is not working! When totalitem gets to 0, which is undefined, the React DOM throws an error:

Uncaught TypeError: Cannot read properties of undefined (reading 'itemTotal')

I really don't know how to solve this issue, and I'm pretty sure that this is a common one. Can anyone please help me out? Thanks a lot in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The first problem (which is triggering the error) is due to accessing itemTotal property on undefined. You can use optional chaining to solve this.

const totalitem = getItem(products.id)?.itemTotal;
const totalitem2 = JSON.stringify(totalitem);

The second problem is checking "undefined" as a string. It should be without quotes.

<h1>{totalitem === undefined ? "Zero!" : totalitem2}</h1>
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