Reputation: 85
I need this solution for my project. its very important for me. i want to update object value with key and index, from local storage FOR my cart application.
(Decrease button for product quantity in cart)
Exmp.
function decreaseQuantity(index) {
var oldQty = localStorage.cart[index].quantity;
var newQty = oldQty - 1;
localStorage.setItem(cart[index].quantity, newQty);
}
Upvotes: 1
Views: 6098
Reputation: 85
its worked for me @PSK thanks for your efforts @adiga I guess I made a logic error. thank you too, for your interest !
Upvotes: 0
Reputation: 17943
You can't store complex object in localStorage
, you can store data as string
only.
If you want to store the cart object to locaStorage
, you need to serialize it as string using JSON.stringify
and store it like following.
window.localStorage.setItem('cart', JSON.stringify(cart));
Note: here 'cart' is the key.
To get back, change it and store back, you need to do like following.
var data = window.localStorage.getItem('cart');
if (data != null) {
let cart= JSON.parse(data);
cart[index].quantity = cart[index].quantity -1;
window.localStorage.setItem('cart', JSON.stringify(cart));
}
Upvotes: 4