Reputation: 60
I'm writing user shopping cart for my portfolio project. I want to save the IDs of products as well as count of how many specific IDs are in my storage. I want my data to look like this:
[
{id: '64783', count: '5'},
{id: '111', count: '50'},
]
Since the data is in localStorage I've user JSON parse and stringify, but I do not know how to achieve the data model in LS I've listed above. Of course i can just store multiple IDs, even when they are the same and then filter it while displaying the shopping cart, but I don't think this is optimal.
export const addToCart = (id, userIsLoggedIn) => {
let cart = [];
let itemToAdd = {
id,
count: 0,
};
if (localStorage.getItem('cart')){
cart = JSON.parse(localStorage.getItem('cart'));
let count = cart.filter(el => el.id === id).length
console.log(count)
}
cart.push(itemToAdd);
localStorage.setItem('cart', JSON.stringify(cart))
console.log(localStorage.getItem('cart'))
};
I can get the value of count correctly, but my function still appends an entire object instead of updating the count of the item.
How can I solve this?
Upvotes: 1
Views: 926
Reputation: 6264
This code will
cart
from localStorage
So, the code is
export const addToCart = (id, userIsLoggedIn) => {
let cart = [];
let itemToAdd = {
id,
count: 1,
};
if (localStorage.getItem('cart')) {
cart = JSON.parse(localStorage.getItem('cart'));
let item = cart.find(el => el.id === id);
if (!item) {
cart.push(itemToAdd);
} else {
item.count ++;
}
} else {
cart = [itemToAdd];
}
localStorage.setItem('cart', JSON.stringify(cart))
console.log(localStorage.getItem('cart'))
};
Alternatively
export const addToCart = (id, userIsLoggedIn) => {
let cart = {};
if (localStorage.getItem('cart')) {
cart = JSON.parse(localStorage.getItem('cart'));
}
cart[id] = (cart[id] || 0) + 1;
localStorage.setItem('cart', JSON.stringify(cart));
console.log(localStorage.getItem('cart'));
};
In this method the cart contents is like
{
"1111": 2,
"1234": 1
}
etc
Upvotes: 1