Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Tadjiev Codes
Tadjiev Codes
9,626 Points

JS Old Cart project question

Dear Treehouse folks and Mr.Steven, I hope you're doing great))) I just wanted to ask regarding my Old project again. Last time you told me, "You'd probably need to search the cart before doing the "points", so when you get to the part that checks the maximum allowed (which comes before the snippet shown here), you could add what's being requested to what's already in the cart and see if the total exceeds the limit."

if (cartItems.find(p => p.productId === itemID) && points === 4) {
                    cartItems[0].quantity++;
                    console.log(cartItems.quantity);
                    alert("Successful incremented purchase of the Timepiece");
                } else {
                    cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
                    displayCartItems();
                }

1) First problem, it adds 0 and -1 items on the display 2) Secondly, it minuses the amount from the total if -1 is used. I think it's not normal and probably not normal that it creates the -1 item in the cart. I tried to change the displayCart function and removed from the function that loads on the body load. So trying to call the addToCart function only when the item is added to the cart. 3) Actually, even all the if statements located inside the function in order to validate how many items added like maxPerCustomer and other things don't seem to work now. The only thing that works is incrementing the same item in the cart but it creates 0 and -1 items in the cart. That's what I'm wondering like what's the fix and why again the conditionals not working once the item in the cart. I commented on this code in js file line 702 as it's not really working. Thankfully, I got a good mark from this project no matter it was duplicating the item. Now I just want to know the solution to this problem not for the mark but for myself. Thanks a lot))) Snapshot of the workspace: https://w.trhou.se/wrh3yw90ow

The link from the previous questions related to the same problem: https://teamtreehouse.com/community/js-project-related-issues

6 Answers

Steven Parker
Steven Parker
231,153 Points

What I meant was to find the item before the test, then test that result. It occurred to me that you don't really need the index, you just need to save the "find" results in a variable:

        if (points === 4) {
            let item = cartItems.find(p => p.productId == itemID);
            if (item) {
                item.quantity++;
                console.log(cartItems.quantity);
                // points++;        // nope, don't need points anymore
                alert("Successful incremented purchase of the Timepiece");
            } else {
                cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
                displayCartItems();
            }
        }

And that extra "points === 5" block you added was just adding a new item into the cart after it was already found to be inside the cart.

Steven Parker
Steven Parker
231,153 Points

Three issues stand out in the snippet:

if (cartItems.find(p => p.productId === itemID) && points === 4) {

You probably don't want to combine these tests, otherwise an item that doesn't have enough "points" to qualify for purchase will still be added to the cart.

                    cartItems[0].quantity++;

This line always increases the count of the first item in the cart, even if a different cart item was the one selected.

                    console.log(cartItems.quantity);

Since "cartItems" is an array, it won't have a "quantity" attribute (so it will always show up as "undefined").

Tadjiev Codes
Tadjiev Codes
9,626 Points

Alright Thank you Mr.Steven) So what Should I use instead of [0] ? within this line

 cartItems[0].quantity++;

That's what I can't understand yet(

Steven Parker
Steven Parker
231,153 Points

You'll want the index of the matching item there. You could use "findIndex" to get it, and if you do it before the test, the result would also indicate if it was found (will be -1 if not).

Tadjiev Codes
Tadjiev Codes
9,626 Points
if (cartItems.find(p => p.productId === itemID)) {
            cartItems.indexOf.quantity++;
            console.log(cartItems.quantity);
            points++;
            alert("Successful incremented purchase of the Timepiece");
        } else {
            cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
            displayCartItems();
        }


        if (points === 5) {
            cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
            displayCartItems();
        }

Am I still ding sth wrong? Now the other validations seem to work but still there's a new cart item instead of incrementing the same. Although it doesn't create 0 and -1 items anymore because of the validations. And I didn't really understand this part of ur previous comment " and if you do it before the test, the result would also indicate if it was found (will be -1 if not)"

Tadjiev Codes
Tadjiev Codes
9,626 Points

Thanks a lot)

function addToCart() {

        var itemID = document.getElementById("addItemId").value;
        var itemIDColor = document.getElementById("addItemId");
        let itemQty = document.getElementById("addItemQty");
        var addQtyValidationMessage = document.getElementById("addQtyValidationMessage");
        var outputErrorQty = document.createElement('p');



        // iterating and validating if item actually exists in our storeItems array, Loved this .filter ES6 method so helpful to iterate and compare in one line
        let obj = storeItems.filter(x => { return x.productId === itemID });
        console.log(itemID);
        console.log(obj);


        let quantityCart = parseInt(document.getElementById("addItemQty").value);

        let points = 0;

        //VALIDATIONS inside the addtoCart function immediately without a seperate validation function

        if (Number.isInteger(quantityCart)) {
            points++;
        } else {
            itemQty.style.borderColor = "#FF0000";
            alert("Please insert the correct number into blank space!");
            outputErrorQty.innerText += 'Please insert the correct number into blank space!';
            addQtyValidationMessage.appendChild(outputErrorQty);
            outputErrorQty.className = "outputProductErNumber"
        }

        if (quantityCart <= 0) {
            alert('Enter an integer number please!');
            itemQty.style.borderColor = "#FF0000";
            outputErrorQty.innerText += 'Enter an integer number please!';
            addQtyValidationMessage.appendChild(outputErrorQty);
            outputErrorQty.className = "outputProductErNumber";
        } else {
            points++;
        }


        if (quantityCart > obj[0].maxPerCustomer) {
            alert(`Unfortunately, We can't let you buy so many timepieces as they're Limited editions`);
            itemQty.style.borderColor = "#FF0000";
            outputErrorQty.innerText += `Unfortunately, We can't let you buy so many timepieces as they're Limited editions`;
            addQtyValidationMessage.appendChild(outputErrorQty);
            outputErrorQty.className = "outputProductErNumber";
        } else {
            points++;
        }

        if (quantityCart > obj[0].quantity) {
            alert(`Unfortunately, We don't have these many watches available in stock `);
            itemQty.style.borderColor = "#FF0000";
            outputErrorQty.innerText += `Unfortunately, We don't have these many watches available in stock `;
            addQtyValidationMessage.appendChild(outputErrorQty);
            outputErrorQty.className = "outputProductErNumber";
        } else {
            points++;
        }
 if (points === 4) {
            let item = cartItems.find(p => p.productId == itemID);
            if (item) {
                item.quantity++;
                console.log(cartItems.quantity);
                // points++;        // nope, don't need points anymore
                alert("Successful incremented purchase of the Timepiece");
            } else {
                cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
                itemIDColor.style.borderColor = "#008000";
                itemQty.style.borderColor = "#008000";
                displayCartItems();
            }
        }



        console.log(cartItems);
        //Calling the function to display the added Items in the cart
        //displayCartItems();
        // calling calculate function here
        calculateCartTotals();

    } // end of the main function

Now the only problem. IF I'm adding number 2 or 3 of items to the cart after let's say one is added. It only ads one item still no matter if it's 2 or 3. Why would that be? But it doesn't create another cart item anymore and increments the same cart item although only increments for 1 always even if that would be 2 or 3.

Steven Parker
Steven Parker
231,153 Points

The unary increment operator you are using (++) always adds just one. Add the desired value instead:

/*old*/         item.quantity++;                // only adds one
/*fix*/         item.quantity += quantityCart;  // adds variable amount

Have you done this course yet? Debugging JavaScript in the Browser

Tadjiev Codes
Tadjiev Codes
9,626 Points

Thank you so much Mr.Steven) Finally can stop looking at the same project) Nope, I haven't done that course yet and didn't even know that it exists. Currently, I've just completed SQL Basics and reached half of the modifying data with SQL. Started PHP basics. And, Just completed OOP JS of Ashley Boucher. Finished her couple of practice courses. Starting the JS OOP Challenge course. I will definitely watch the course you have recommended today and there's another one with DEV tools that I wanna complete from Treehouse. Thanks a lot for suggesting always sth helpful about the courses and everything. The reason I've started PHP and SQL because I have these units in the new semester. In the first one, we were using Microsoft Access and a few SQL statements. But now its only SQL unit and PHP unit, OOP JS, CMS, Design Graphics, Business. Do you think I should give a try to do the JS Fullstack Techdegree? The problem I'm already overwhelmed with the College courses that I have now.

Steven Parker
Steven Parker
231,153 Points

As you say, college is pretty demanding so you might want to focus on that for now. But if you have the time for extra study, there's also the Full Stack JavaScript track.

Tadjiev Codes
Tadjiev Codes
9,626 Points

Thanks a lot for all the suggestions and support 😊