Reputation: 13
The console spits out: "TypeError: tempItem is undefined [...] app.js:145:21"
despite tempItem being declared already (the ellipses are my way of showing space by the way in case that wasn't apparent).
For reference, I am JS noobie looking into how e-commerce sites handle their shopping cart mechanisms as I'd like to try my own version. The mechanism in question is the "adding item amount from the cart overlay" mechanism.
So at first glance I thought that this was probably caused by a typo somewhere. Okay, no biggie, I will just change it in a jiffy. Two agonizing hours in and I am beating myself up over this as I am unable to tell what is wrong with what I did. Everything seems to line up according to how I planned it. Here's the snippet of code in question, from line 141 to 149:
else if (event.target.classList.contains("fa-chevron-up")) {
let addAmount = event.target;
let id = addAmount.dataset.id;
let tempItem = cart.find(item => item.id === id);
tempItem.amount = tempItem.amount + 1;
Storage.saveCart(cart);
this.setCartValues(cart);
addAmount.nextElementSibling.innerText = tempItem.amount;
}
So the console is reading tempItem as being undefined, but in the code I see tempItem being declared let tempItem...;
so what gives? As the result of this error, the "fa-chevron-up"
button that I am using for the add mechanic does nothing. I read and re-read through my entire code to make sure that there weren't any typos. Maybe I am becoming dyslexic, or I am too tired. I feel dumb for struggling with what should be a self-explanatory problem.
Just in-case I am not psyching myself, here's the screenshot of the code that I've been glaring at: https://i.sstatic.net/xmqSI.jpg
Thank you in advance.
Edit 1: Thank you for the responses. So here is what the cart looks like, in the first picture: https://i.sstatic.net/TgHvu.jpg I can add stuff unto here, the "remove" and "clear cart" buttons work as planned, but the chevrons do not work. They do nothing. The second photo included in the same link is the html format that I am interpolating.
Upvotes: 1
Views: 56
Reputation: 18619
Array#find
returns undefined
when it checked every element, and found no match.
Try to test whether there are a match:
let addAmount = event.target;
let id = addAmount.dataset.id;
let tempItem = cart.find(item => item.id === id);
if(typeof tempItem !== "undefined"){
tempItem.amount = tempItem.amount + 1;
Storage.saveCart(cart);
this.setCartValues(cart);
addAmount.nextElementSibling.innerText = tempItem.amount;
}else{
console.log('No match')
}
Upvotes: 1
Reputation: 61
Unless the find below succeeds, you will get an undefined as the response.
let tempItem = cart.find(item => item.id === id);
Also, item.id and id have to be of the same type since you are using the stricter === operator.
So there can be two reasons for this undefined being returned:
Upvotes: 0