Search code examples
javascriptarraysjsonstringifysession-storage

How to store data in array to be stringified (javascript)


Just started JS, have read a bunch of SO answers like this or this one or this other one, but still having trouble getting this to work. I have a list of inventory items, whenever one is clicked, I want the id of that one (stored as a data attribute) to be pushed to a sessionStorage cart object. Not functioning code below, comments show what the output is. It looks like I'm having a problem JSON.stringifying the array.

Help greatly appreciated.

    var cart = [];
    $(document).on("click", "#inventory", function() { // let's say i clicked on the #inventory whose data attribute for inventory_id is 13
      console.log($(this).data('inventory_id')) // outputs 13
      cart.push($(this).data('inventory_id')) 
    });
    console.log(cart) // outputs an array where Array[1] = 13 in last example
    console.log(JSON.stringify(cart)) // outputs a blank: []
    localStorage.setItem("cart", JSON.stringify(cart));
    console.log(localStorage.getItem("cart"))  // outputs a blank: []

Solution

  • Per comments discussion, right answer was just to put the localStorage.setItem in the event handler itself.

    var cart = [];
    $(document).on("click", "#inventory", function() { // let's say i clicked on the #inventory whose data attribute for inventory_id is 13
      cart.push($(this).data('inventory_id'));
      localStorage.setItem("cart", JSON.stringify(cart));
    });