Search code examples
javascriptreactjsnext.jscart

Getting error when try to find existing product from localStorage in JavaScript


I am trying to implement a cart system using localStorage, the codes are below, how I trying to achieve that

const data = {
    description: "Cum sociis natoque",
    mediaUrl: "/products-img7.jpg",
    name: "Hearing Aid Device",
    newProduct: true,
    onOffer: "5",
    onSale: true,
    price: "99.57",
    productType: "medical",
    sku: "534-20-2675",
    viewCount: 0,
    _id: "5f095b0bd7f2be792ee6ba1c",
}

const handleAddToCart = (data, quantity = 1) => {
    let getCarts = JSON.parse(localStorage.getItem('myCart'))
    let existed_item = null
    if(getCarts || getCarts != null){
        existed_item = getCarts.find(item => item._id == data._id) // Error in that line
    }

    if (existed_item) {
        let cartItem = Object.assign({}, existed_item, {quantity: (quantity + existed_item.quantity)})
        localStorage.setItem('myCart', JSON.stringify(cartItem))
    } else {
        let cartProducts = new Array()
        if(localStorage.getItem('myCart')){
            cartProducts = JSON.parse(localStorage.getItem('myCart'))
        }
        let dataWQty = Object.assign({}, data, {quantity: quantity});
        let newCartProducts = [...cartProducts, dataWQty]

        localStorage.setItem('myCart',JSON.stringify(newCartProducts));
    }
}

from above codes getting below error

Unhandled Runtime Error <br/>
TypeError: getCarts.find is not a function

How can I overcome that situation now? I really want a help to solve that.

Thanks in Advance.


Solution

  • I think you need to change your logic for updating the items while you are getting array at first but you are replacing it with an object when you are first updating it

    let getCarts = JSON.parse(localStorage.getItem('myCart'))
    let existed_item_index = -1
    if(getCarts || getCarts != null){
        existed_item_index = getCarts.findIndex(item => item._id === data._id)
    }
    
    if (existed_item_index!==-1) {
        const updatedCarts = JSON.parse(JSON.stringify(getCarts));
        updatedCarts[existed_item_index].quantity += quantity;
        localStorage.setItem('myCart', JSON.stringify(updatedCarts));
    }