Search code examples
javascriptarraysjsonnulllocal-storage

web browser local storage return value is null but it's not shown as a null value in JavaScript


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)

Solution

  • localStorage.setItem saves value as stringified for non string values. You need to check the value against "null" or after JSON.parse.

    Suggest always use the following wrapper utils to while using localStore

    const getLocalStorageValue = (key, defaultValue = undefined) => {
      const strValue = localStorage.getItem(key);
      let value = defaultValue;
      if (strValue) {
        try {
          value = JSON.parse(strValue);
        } catch ({ message }) {
          // execption
          console.info("Caught error while JSON parse", message);
        }
      }
      return value;
    };
    
    const setLocalStorageValue = (key, value) => {
      try {
        const valueStr = JSON.stringify(value);
        localStorage.setItem(key, valueStr);
      } catch ({ message }) {
        // execption
        console.info("Caught error while JSON stringify", message);
      }
    };