0

I'm new to working with both JSON and localStorage.

I am trying to create a small client-side "basket" of sorts which stores a productID in my localStorage under the title cart.

At present, my cart localStorage item is overwritten with a new productID instead of having the productID added as a new item. Of course the cart object should be able to accept multiple items.

Here is my codepen: http://codepen.io/franhaselden/pen/regVgj

My addToCart function is really simple, but I'd not adding the right JSON structure. I'm confused over what the JSON structure should be in this case where multiple items are added but the key is the same (productID)

function addToCart(productID) {
  localStorage.setItem('cart', JSON.stringify(productID));
}

1 Answer 1

3

Use an array:

function addToCart(productID) {
  // Get stored array, if it's not set, it should be set to an empty array
  var basket = localStorage.getItem('cart');
  basket = basket ? JSON.parse(basket) : [];

  basket.push(productID);
  localStorage.setItem('cart', JSON.stringify(basket));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.