I am trying to store cart data in localstorage, I am starting out so I want to store all the products in localstorage using store.js
I want to store the name, price and quantity of each added item to the cart.
Here's what I am doing so far:
$('.proAdd').click(function(){
var name = $(this).attr("data-name");
var price = parseFloat($(this).attr("data-price"));
var quantity = parseInt($(this).attr("data-quantity"));
store.set('item', { name:name, price:price, quantity:quantity })
});
So this is ok if I just have one item in the cart, when I add another product it overwrites the item object. How can I turn this into an array of objects so that when I add another it could look like this:
{"name":"T-Shirt","price":3.99,"quantity":1}, {"name":"Blue Jeans","price":13.99,"quantity":1}
Any help would be appreciated. Cheers.
You have to think of the localStorage field as an array with potential data from the beginning.
In code:
// 1. and 2. where `items` is always an array of item-objects with 0..n elements const items = (() => { const fieldValue = localStorage.getItem('cart'); return fieldValue === null ? [] : JSON.parse(fieldValue); })(); // 3. items.push({"name":"T-Shirt","price":3.99,"quantity":1}); // 4. localStorage.setItem('cart', JSON.stringify(items));Or with storejs:
// 1. and 2. where `items` is always an array of item-objects with 0..n elements const items = store.get('cart') || []; // 3. items.push({"name":"T-Shirt","price":3.99,"quantity":1}); // 4. store.set('cart', items);