skip to Main Content

enter image description here

Here’s my local storage key-value pair

ProductsInCart : null

when I access it in JavaScript in flowing line,

let cartItemsList = localStorage.getItem("ProductsInCart");
            console.log(cartItemsList)

cartItemsList value is null,

But when I check it with the following condition,

if (cartItemsList != null) {
                
                console.log('not null')
            } else {
                console.log('null')
            }

the out put is not null,

Here is my original JavaScript code ,

 var imgSrc = JSON.parse(sessionStorage.getItem('storedSingleProductImage'))
        MainImg.src = imgSrc;

        var sProductCategory = document.querySelector('#productCategory')
        var sProductName = document.querySelector('#productName')
        var sProductPrice = document.querySelector('#productPrice')
        var sNumberOfproducts = document.querySelector('#numberOfproducts');

        let sProdCategory = JSON.parse(sessionStorage.getItem('storedSingleProductCategory'))
        let sProdName = JSON.parse(sessionStorage.getItem('storedSingleProductName'))
        let sProdPrice = JSON.parse(sessionStorage.getItem('storedSingleItemPrice'))

        sProductCategory.innerHTML = sProdCategory
        sProductName.innerHTML = sProdName
        sProductPrice.innerHTML = sProdPrice
        let sNumberOfprod =1;
        sNumberOfproducts.addEventListener('input', () => {
             sNumberOfprod = sNumberOfproducts.value;
        });
        function addToCart() {

            let cartItemsList = localStorage.getItem("ProductsInCart");
            console.log(cartItemsList)

            let cartItems = [];
            //this condition true for null values also
            if(cartItemsList !== null){

                //I want parse a not null value for the JSON.parse() because it will pop a error otherwise
                 cartItems =  JSON.parse(cartItemsList);
            }
  
            cartItems.push(
                {
                    sProdCategory,
                    sProdName,
                    sProdPrice,
                    sNumberOfprod,
                    imgSrc
                }
            )
            localStorage.setItem("ProductsInCart", JSON.stringify(cartItems));
            alert(`${sNumberOfprod} items of ${sProdName}-(${sProdCategory}) added to the cart.`)
        }

this the out put of the code

Uncaught TypeError: Cannot read properties of null (reading 'push')
    at addToCart (sproduct.html:154:23)
    at HTMLButtonElement.onclick (sproduct.html:54:58)

3

Answers


  1. You should set the items first and should check the localstorage in the console of the web browser.

    localstorage.setItem("ProductsInCart");
    console.log("localstorage");
    
    Login or Signup to reply.
  2. You have not parsed your JSON object before if condition Use JSON.parse while get the data from localStorge.

    let cartItemsList = JSON.parse(localStorage.getItem("ProductsInCart"));
    let cartItems = [];
     //this condition true for null values also
    if(cartItemsList !== null){
    //I want parse a not null value for the JSON.parse() because it will pop a error otherwise
     cartItems =  JSON.parse(cartItemsList);
    }
    
    Login or Signup to reply.
  3. In local storage all values are stored as String and hence when you get item it is returning:-

    cartItemsList = "null" and not cartItemsList = null
    

    So Either you remove double quotes from the string "null" before checking like this:-

     cartItemsList = cartItemsList.replace(/['"]+/g, '')
    

    Or you check your condition as "null" like:-

    if (cartItemsList != "null")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search