Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading