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.
CodePudding user response:
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>