Daniel Skoroś
Daniel Skoroś

Reputation: 60

How to count specific ID's in localStorage?

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

Answers (1)

Bravo
Bravo

Reputation: 6264

This code will

  1. read the cart from localStorage
  2. check if the id exists in the cart
  3. if it does, increment the count
  4. otherwise add the item with count:1
  5. if the localStorage is empty, it creates the whole object

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

Related Questions