I’m learning about localStorage and I’m trying to build a basic shopping cart function. The process is:
- user clicks on "Add To Cart" button.
- If localStorage("shoppingCart") doesn’t exist, then localStorage.setItem("shoppingCart", itemToAdd).
- 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 = [];
- clear the localStorage,
- push the itemToAdd object to the updatedShoppingCart array.
- 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
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.
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 :