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

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

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