How do I save the items of a shopping cart in the local storage?

Hello ldsub67, Be tension free, I’ve got solution for your error. Even after refreshing the screen the cart and subtotal remains as it is. Just follow few steps below as:

Step 1: Make changes in context.js file and in addToCart(id)

addToCart = (id) => {
        let tempProducts = [...this.state.products];
        const index = tempProducts.indexOf(this.getItem(id));
        const product = tempProducts[index];
        product.inCart = true;
        product.count = 1;
        const price = product.price;
        product.total = price;
        this.setState(() => {
            return { products: tempProducts, cart: [...this.state.cart,
            product] };
        },
        () => {
            this.addTotal();
            localStorage.setItem('myCart', JSON.stringify(this.state.cart))
        });
    }

Step 2: Now in componentDidMount()

componentDidMount = () => {
        this.setProducts();
        const cart = localStorage.getItem('myCart')
        this.setState({cart: JSON.parse(cart) ? JSON.parse(cart) : []}, this.addTotal)
    }

And this the ultimate solution. Please do comment once you have made changes.

1 Like

Hello,

there is a better way to save the cart without localstorage or sessionstorage or cookies.??

You can try firebase or mongodb… better would be firebase storage. There’s lot of tutuorials available online