Reza Del Reza Del - 5 months ago 26
Javascript Question

Cannot read property 'push' of null Javascript Shopping Cart

I have fallowed online tutorial on how to build Shopping Cart using javascript and now facing an error when i want to add the first item to the cart.
i am getting and error of

Cannot read property 'push' of null

and the code is trying to add item to the cart array list
i have tried to debug the code and i can see there is value in the array but still getting an error

the part that show an error is

// add item to the cart with name , price , count
function addItem(name , price , count)
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name we want to enter with the name in cart
{
cart[i].count += count;
return;
}
}
var item = new Item (name , price , count);

alert(item);
console.log(item);
cart.push (item);// **getting an error in here**
saveCart ();

}


the full code is :

<html>
<head>
<title>Shopping Cart</title>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<h1>Shopping Cart</h1>
<div>
<ul>
<li><a class ="addtoCart" href="#" data-name="apple" data-price="1.22">Apple</a></li>
<li><a class ="addtoCart" href="#" data-name="orange" data-price="2.22">Orange</a></li>
<li><a class ="addtoCart" href="#" data-name="banana" data-price="3.22">Banana</a></li>
<li><a class ="addtoCart" href="#" data-name="kiwi" data-price="4.22">Kiwi</a></li>
</ul>
<button id="cleareCart">Clear Cart</button>
</div>
<div>
<ul id="showCart"></ul>

</div>
<script>
//jQuery
$(".addtoCart").click(function(event)
{
event.preventDefault();
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
addItem(name , price, 1);
displayCart();
}
);
function displayCart ()
{
var CartArray = listCart ();
var outPut = "";
for (var i in CartArray)
{
outPut += "<li>"+CartArray[i].name+" "+ CartArray[i].count+"</li>"
}
$("#showCart").html(outPut);
}

//******************************************Javascript/// shopping cart functions
var cart =[];// this is array that contain all the shopping cart item
// we need to display:
/*name ,price,count, id */
var Item =function (name , price , count)// add item to the cart array
{
this.name = name
this.price = price
this.count = count
}
/*Cart Functions : what are cart need to do

load the cart ()// load from localstorage
*/
// add item to the cart with name , price , count and id of the item
function addItem(name , price , count)
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name we want to enter with the name in cart
{
cart[i].count += count;
return;
}
}
var item = new Item (name , price , count);

alert(item);
console.log(item);
cart.push (item);
saveCart ();

}
//remove the item from the cart with name, price , count , id (one item only)
function removeItemFromCart (name, count)
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name of the item with the item in cart
{
cart[i].count = cart[i].count-count;
if (cart[i].count === 0 )
{
cart.splice(i,1);
}
break;
}
}
saveCart ();
}
//remove the item from cart all (name) this will remove all of the item name
function removeAllItem (name)// remove all of the one item from cart (if the count is more than one )
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name of the item with the item in cart
{
cart.splice(i,1);
break;
}
}
saveCart ();
}
function clareCart ()// remove everything from the cart
{
cart = [];
saveCart ();
}
function countCart ()// return the total cumber of the items in the cart
{
var totalCount = 0 ;
for (var i in cart )
{
totalCount += cart[i].count;
}
return totalCount;
}
function totalCartCost ()
{
var totalCost = 0 ;
for (var i in cart )
{
totalCost += cart[i].price;
}
return totalCost;
}
function listCart ()//array of items // array of the cart that we can use to generate HTML
{
var cartCopy = [];
for (var i in cart)
{
var item = cart[i];
var itemCopy = {};
for (var p in item)
{
itemCopy[p] = item[p];
}
cartCopy.push (itemCopy);
}
return cartCopy;
}
function saveCart ()// localstorage
{
localStorage.setItem("testCart", JSON.stringify(cart));
}
function loadCart ()// load the cart
{
cart = JSON.parse(localStorage.getItem("testCart"));
}
//addItem('', null , null );
// addItem('apple',1.22 , 1);
// addItem('apple',1.22 , 1);
// addItem('apple',1.22 , 3);
// addItem('orange',1.22 , 3);

//console.log(cart);
// console.log(cart);
//removeAllItem('apple');
// console.log(cart);
// console.log (countCart()) ;

//console.log (listCart());

loadCart();
var Array = listCart();
console.log (Array);
</script>
</body>




any help would be appreciated

Answer

i have found my own problem after 5 days of looking at the code

  function loadCart ()// load the cart 
    {
        cart = JSON.parse(localStorage.getItem("testCart"));

    }

load cart is trying to load a Json file that it does not exist yet and then there is no cart so it give me an error

to fix that i add this

        function loadCart ()// load the cart 
    {
        cart = JSON.parse(localStorage.getItem("testCart"));
         if (cart === null) {
             cart = [];
            }
    }