'An error arises when I add a key value to an object

As the title says, I need a code to make this work. The code is:

let count = 0;
for (const payment of paymentButtons) {
    if (payment.checked) {
        count = 0;
        window.confirm(acc+" added "+quantity+" sized: "+size+" "+name+" for "+price+" with "+shipping+" to cart");

        let count2 = 1;
            
        var tocart = {
            name: name,
            price: price,
            size: size,
            quantity: quantity,
            shipping: shipping
        };

        console.log(tocart)

        var cart = JSON.parse(localStorage.getItem("cart"));
        for (const key in cart) {
            count2++;
        }

        var naming = "tocart"+count2.toString();
            
        cart[naming] = tocart;
        console.log(cart)
            
        var json = JSON.stringify(cart);
        localStorage.setItem("cart", json);
            
        break;
    }
}

but it gives an error of type:

Uncaught TypeError: Cannot set properties of null

I have tried everything I could but I couldn't find the answer. how can I make it to add the key value to the object?



Solution 1:[1]

Are you sure that localStorage has an object with key 'cart'?

localStorage.getItem("cart")

You can add default value (empty object) for the case of it has not:

var cart = JSON.parse(localStorage.getItem("cart")) ?? {};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergey Plishka