Currently working on an e-commerce website, which is my first major project. I am, for the first time, implementing localstorage for the basket date (qty, items etc).
What I am trying to achieve is whenever the user clicks on the 'add to basket' button, the number beside the basket increases and displays. This is pretty straightforward but with localstorage I am obviously doing something wrong. I assume I am retrieving it incorrectly?
Please can you explain to me what I am doing wrong here as I want to get my head wrapped around how to use local storage in this scenario correctly. I thinkk that will help me understand how to implement it correctly when it comes to parseing the JSON product details correctly too.
Please have a look at the code below.
let basketData = {
basketQty: 0,
products: []
}
//LOCAL STORAGE
localStorage.setItem("basketData", JSON.stringify(basketData));
let localData = JSON.parse(localStorage.getItem("basketData"));
//INCREASE BASKET QTY INNER HTML
addToBasket.click(function(){
basketData.basketQty++;
if (basketData.basketQty > 0){
$(basketQty).html(localData.basketQty);
}
})
<nav>
<div class="logo">
<img src="images/logo.png" alt="Prime Health Logo" />
</div>
<div class="nav-links">
<ul>
<li>VITAMIN & SUPPLEMENTS</li>
<li>SPORTS & WORKOUT NUTRITION</li>
<li>WEIGHT MANAGEMENT</li>
<li>FREE FROM</li>
</ul>
</div>
<div id="basket">
<span id="item-count"></span>
<i class="fas fa-shopping-basket"></i>
</div>
</nav>
Many thanks for taking the time out to help and respond!