skip to Main Content

I’m learning about localStorage and I’m trying to build a basic shopping cart function. The process is:

  1. user clicks on "Add To Cart" button.
  2. If localStorage("shoppingCart") doesn’t exist, then localStorage.setItem("shoppingCart", itemToAdd).
  3. If localStorage("ShoppingCart) DOES exist (which for testing purposes, it does) then bring in the JSON string and parse it into an initialized array called updatedShoppingCart = [];
  4. clear the localStorage,
  5. push the itemToAdd object to the updatedShoppingCart array.
  6. Then set the updatedShoppingCart array to local storage with localStorage.setItem("shoppingCart", JSON.stringify(updatedShoppingCart)) for later usage in shopping process.

but I keep getting the TypeError: updatedShoppingCartArray.push is not a function
at HTMLButtonElement.addToCart
error on step #5.

Here’s my code:

// simulate a product in the localStorage.
let prepTesting = {
   name: "Tshirt: Enter the Red Dragon",
   price: 3225,
   qty: 1
};

localStorage.setItem("shoppingCart", JSON.stringify(prepTesting));


// Get values from product index.html page
let order_item_name = document.getElementById('order_item_name');
let order_item_price = document.getElementById('order_item_price');
let order_item_qty = document.getElementById('order_qty');

// initialize buttons
const btn_addToCart = document.getElementById('btn_addToCart');
const btn_clrLocalStorage = document.getElementById('btn_clrLocalStorage');

// set object with product order values
let itemToAdd = {
   name: order_item_name.dataset.name,
   price: parseInt(order_item_price.dataset.price),
   qty: parseInt(order_item_qty.value)
};

function clrLS(e) {
   e.preventDefault();
   localStorage.clear();
   location.reload();
}

function addToCart(e) {
   e.preventDefault();

   // assign localStorage("shoppingCart") to shoppingCart to check if it exists
   let shoppingCart = localStorage.getItem("shoppingCart");

   if (shoppingCart === null) {
      // push itemToAdd to localStorage
      localStorage.setItem("shoppingCart", JSON.stringify(itemToAdd));
   }else {
      // initialize array to insert localStorage array
      let updatedShoppingCartArray = [];

      // get and insert localStorage into updatedShoppingCartArray
      updatedShoppingCartArray = JSON.parse(localStorage.getItem("shoppingCart"));

      // clear localStorage for clean setting.
      localStorage.clear();

      // push itemToAdd into updatedShoppingCartArray
      // This is where I get the "updatedShoppingCartArray.push is not a function" error
      updatedShoppingCartArray.push(itemToAdd); 
      console.log(updatedShoppingCartArray);

      // set updatedShoppingCart to localStorage
      localStorage.setItem("shoppingCart", JSON.stringify(updatedShoppingCartArray));
   }
}

btn_addToCart.addEventListener('click', addToCart);
btn_clrLocalStorage.addEventListener('click', clrLS);

I believe my pseudo-code is correct and I can’t figure out what the issue is with the error when running the script.

Any guidance would be appreciated. Thank you.

2

Answers


  1. localStorage.setItem("shoppingCart", JSON.stringify([prepTesting]));
    
    //...
    
    if (shoppingCart === null) {
      // push itemToAdd to localStorage
      localStorage.setItem("shoppingCart", JSON.stringify([itemToAdd]));
    }
    

    You need to put your initial item into an array.

    At the moment, you are putting the initial object in as an object, not an array with a single object in it.

    Login or Signup to reply.
  2. The error updatedShoppingCartArray.push is not a function occurs because updatedShoppingCartArray is not an array. When you retrieve an item from localStorage, it’s parsed as an object, not an array, since you originally stored an object. You need to ensure updatedShoppingCartArray is always an array before trying to push new items into it.

    Explanation:

    Check if shoppingCart exists: localStorage.getItem("shoppingCart") returns null if the key doesn’t exist.

    If it doesn’t exist: Initialize the shopping cart with an array containing itemToAdd.

    If it exists: Parse it using JSON.parse(shoppingCart).
    Check if the parsed result is an array using Array.isArray().

    If it’s not an array, convert it to an array containing the existing item.

    Push the new item: Add the new item to the array and update localStorage.

    This approach ensures that updatedShoppingCartArray is always an array before attempting to use push.

    Here is revised version of your code :

    function addToCart(e) {
       e.preventDefault();
    
       // assign localStorage("shoppingCart") to shoppingCart to check if it exists
       let shoppingCart = localStorage.getItem("shoppingCart");
    
       if (shoppingCart === null) {
          // If no shopping cart exists, create one with the current item
          localStorage.setItem("shoppingCart", JSON.stringify([itemToAdd]));
       } else {
          // parse shoppingCart into an array
          let updatedShoppingCartArray = JSON.parse(shoppingCart);
    
          // Check if updatedShoppingCartArray is an array
          if (!Array.isArray(updatedShoppingCartArray)) {
             // If it's not an array, convert it to an array containing the existing item
             updatedShoppingCartArray = [updatedShoppingCartArray];
          }
    
          // push itemToAdd into updatedShoppingCartArray
          updatedShoppingCartArray.push(itemToAdd);
          console.log(updatedShoppingCartArray);
    
          // set updatedShoppingCart to localStorage
          localStorage.setItem("shoppingCart", JSON.stringify(updatedShoppingCartArray));
       }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search