-1

I am trying to add products to the cart in my website with localStorage, so I initialize an array and then push products into it. The problem is when I use JSON.parse() to push a product and then stringify it again with JSON.stringify() it returns a number instead of the array. This is the part of my code that throws an error:

let product = {
                id: i + 1,
                name: productNames[i].innerText,
                price: prices[i].innerHTML,
                img: imgs[i].src
            };

            if(localStorage.productsInCart) {
                let productsInLocalStorage = JSON.parse(localStorage.getItem("productsInCart") || "[]");
                console.log(productsInLocalStorage);
                let newArray = productsInLocalStorage.push(product);
                console.log(JSON.stringify(newArray));
                localStorage.productsInCart = JSON.stringify(newArray);
                numberOfProducts.innerHTML = parseInt(numberOfProducts.innerHTML, 10) + 1;

            } else {
                let productToStore = JSON.stringify([product]);
                localStorage.setItem("productsInCart", productToStore);
                numberOfProducts.style.display = "block";
                numberOfProducts.innerHTML = 1;
            };

And then in the console: enter image description here

That circled 2 is the console.log() of the JSON.stringify. I have been searching for detailed info about this but nothing seems to work.

1 Answers1

1

The trouble is this line:

let newArray = productsInLocalStorage.push(product);

From the MDN Docs: The push() method adds one or more elements to the end of an array and returns the new length of the array. (emphasis mine)

You're assigning the length of the array to newArray.

Brendan Bond
  • 1,737
  • 1
  • 10
  • 8