I’m trying to access an object in localStorage but it keeps returning undefined in the console.log

Issue

This Content is from Stack Overflow. Question asked by davidhowe1

I’m building out the shopping cart and functionality for a website that sells merchandise and have come across an issue that i’m stumped on.

To build the merchandise page with all the cards featuring details of the items for sale (picture, title, price description etc) i’ve used an array of objects and a for loop to render the HTML dynamically. Each card has a buy button that adds the item to the cart and which is also rendered dynamically. Each cart item has a remove button.

I’m up to the stage where I’m building the local storage to keep the items on the page should the user refresh the page or close the browser and return later.

To do this, I’ve used local-storage to store keys and values (cart value, cart items count and the items themselves) for access later on. When a user clicks the add to cart button, the local-storage keys are updated with the cart total, price and the objects representing the items in the cart.

Where i’m stuck is with the remove cart item button which, when clicked, should access the corresponding item in the local storage and remove it.

While building out the logic for this function removeItems() I tried to console.log the object in the local storage but all I’m getting is undefined. I’ve tried creating the elements on the merchandise page straight in the DOM instead of dynamically, checked for spelling mistakes and created a ready state function to make sure the elements are all loaded before proceeding but still I’ve had no luck getting the console to log the object in the

The code is below for you to see but unfortunately local-storage is unavailable. Please see a snippet of the javascript below. There you can also see the HTML injected into the DOM.

let merchCards = [

  {
    id: "fikacoffeecup",
    pictureUrl: "pictures/fika1-square.jpg",
    alt: "FIKA Coffee Cup",
    title: "Fika Coffee Cup",
    description: "FIKA official coffee cups. Complete with a message of the day.",
    price: 2.99,
    inCart: 0
  },

  {
    id: "blondies",
    pictureUrl: "pictures/fika2-square.jpg",
    alt: "Closeup of FIKA Blondies",
    title: "Blondies",
    description: "Famous Fika Blondies. Indulge in these super fudgy delights!",
    price: 8.99,
    inCart: 0
  },

  {
    id: "pastramisandwich",
    pictureUrl: "pictures/fika3-square.jpg",
    alt: "Close up of FIKA Pastrami Sandwich",
    title: "Pastrami Sandwich",
    description: "Classic Pastrami, straight out of the NY deli, brought to you here in Liverpool.",
    price: 5.99,
    inCart: 0
  },

  {
    id: "royalbrownies",
    pictureUrl: "pictures/fika6.jpg",
    alt: "Closeup of FIKA brownies",
    title: "Royal Brownies",
    description: "Celebrate the Jubilee this year with these caramel cornflake brownies!",
    price: 5.99,
    inCart: 0
  },

];

let htmlCode = ``;

merchCards.forEach(function(merchCardObjects) {
  htmlCode =
    htmlCode +
    `
     <div id="${merchCardObjects.id}" class="merch-card">
         <div class="picture-wrapper"> 
             <img class="merch-image" src="${merchCardObjects.pictureUrl}" alt="${merchCardObjects.alt}">
         </div>
 
         <div class="text-wrapper">
             <h2 class="title" >${merchCardObjects.title}</h2>
             <h3 class="price">£${merchCardObjects.price}</h3>
             <p class="description" >${merchCardObjects.description}</p>
 
             <button class="add-to-cart" id="buy-btn">Add to Cart</button>
         </div>
             
     </div>
     `
});

let merchCardsRendered = document.querySelector('.main-container')
merchCardsRendered.insertAdjacentHTML('beforeend', htmlCode)

// Cart Code

let cartToggle = document.querySelector('#cart-toggle-tab')

cartToggle.addEventListener('click', toggleCart)

function toggleCart() {
  let toggleCart = document.getElementById('cart')
  let toggleButton = document.getElementById('cart-toggle-tab')
  toggleCart.classList.toggle('hide')
  toggleButton.classList.toggle('hide')
}

let addToCart = document.querySelectorAll('#buy-btn.add-to-cart')

for (let i = 0; i < addToCart.length; i++) {
  addToCart[i].addEventListener('click', () => {
    totalItems(merchCards[i]);
    totalCost(merchCards[i])
    showCartItems(merchCards[i])
  });
}

function onLoadCartItems() {
  let mobileCart = document.querySelector('#total')
  let productNumbers = localStorage.getItem('cart-total')

  if (productNumbers) {
    mobileCart.textContent = productNumbers
  }
}

function totalItems(item) {
  let productNumbers = localStorage.getItem('cart-total')
  let mobileCart = document.querySelector('#total')
  productNumbers = parseInt(productNumbers)

  if (productNumbers) {
    localStorage.setItem('cart-total', productNumbers + 1)
    mobileCart.textContent = productNumbers + 1
  } else {
    localStorage.setItem('cart-total', 1)
    mobileCart.textContent = 1
  }

  setItems(item)
}

function setItems(item) {
  let cartItems = localStorage.getItem('items-in-cart')
  cartItems = JSON.parse(cartItems)

  if (cartItems != null) {
    if (cartItems[item.title] == undefined) {
      cartItems = {
        ...cartItems,
        [item.title]: item
      }
    }
    cartItems[item.title].inCart += 1

  } else {
    item.inCart = 1
    cartItems = {
      [item.title]: item
    }
  }

  localStorage.setItem('items-in-cart', JSON.stringify(cartItems))
};

function totalCost(item) {
  let totalPrice = localStorage.getItem('total')

  if (totalPrice != null) {
    let = totalPrice = parseFloat(totalPrice)
    localStorage.setItem('total', totalPrice + item.price)
  } else {
    localStorage.setItem('total', item.price)
  }
};

function showCartItems() {
  let cartItems = localStorage.getItem('items-in-cart')
  let itemsContainer = document.querySelector('.cart-row-container')
  cartItems = JSON.parse(cartItems)

  let total = document.querySelector('.grand-total')
  let totalPrice = localStorage.getItem('total')
  totalPrice = Math.round(totalPrice * 100) / 100
  total.textContent = "Grand Total: £" + totalPrice


  if (cartItems && itemsContainer) {
    itemsContainer.innerHTML = ''
    Object.values(cartItems).map(item => {
      itemsContainer.innerHTML += `
            <div class="cart-row" id="${item.id}">
                <div class="row-container">
                    <img class="image" src="${item.pictureUrl}" alt="${item.alt}"></img>
                    <div class="title">${item.title}</div>
                </div>
                <div class="row-container">
                    <div class="price"><p>${item.price}</p></div>
                    <input class="quantity" type="number" value="${item.inCart}">
                </div>
                <div class="row-container">
                    <button class="remove-item">&#x2715</button>
                </div>
            </div>
            `
    });
  }

  removeItems();

}

function removeItems() {
  let removeButtons = document.querySelectorAll('.remove-item')
  let itemName;
  let cartItems = JSON.parse(localStorage.getItem('items-in-cart'))

  for (let i = 0; i < removeButtons.length; i++) {
    removeButtons[i].addEventListener('click', function() {
      itemName = removeButtons[i].parentElement.parentElement
        .firstElementChild.lastElementChild.textContent.toLowerCase().replace(/ /g, "");
      console.log(cartItems[itemName])
    })
  }
}

onLoadCartItems()
showCartItems()



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?