To work around this issue, one solution is to store an array of objects where each object represents a basket with the product ID as the key. This approach provides more clarity and simplicity compared to saving all objects in a single container.
- Start by fetching all the required baskets and organizing them into an array:
const basket = [{productId: 2, quantity:5}, {productId: 6, quantity: 4}, {productId: 4, quantity: 18}, {productId: 3, quantity: 5}]
Save the basket array in localStorage:
localStorage.setItem('basketContainer', JSON.stringify(basket))
When it's time to update the list/array, retrieve the basketContainer from localStorage and iterate through it.
const update = JSON.parse(localStorage.getItem('basketContainer'))
update.forEach(item => {
if (item.productId == 4) {
item.quantity += 1
}
})
You can log the 'update' variable at this stage to see the changes reflected.
Similarly, create a function for incrementing or decrementing quantities:
const incrementDecrement = (list, action) => {
update.forEach(item => {
if (item.productId == 4) {
// Use action parameter to determine increment (+) or decrement (-)
item.quantity `${action}`= 1
}
})
}
After making updates, save the data back to your localStorage using the same name:
localStorage.setItem('basketContainer', JSON.stringify(update))
Best of luck implementing these changes!
It's also recommended to consider alternatives to local storage. For further insights, check out this article: stop_using_localStorage