I didn’t get any more answers in my other thread, so I’ll start a new one.
Anyways, I made a shopping cart with ReactJS and I would like that the product information and the prices stay in the cart component when I refresh.
For that, I wanted to save them in the local storage. But every time I refresh after adding a product to the cart, nothing is being displayed but an empty cart although the stuff is in the local storage as I can see with the developer tools of the browser.
The object in the local storage is a unified object of several items (see below).
At any rate, I can’t seem to find out where the mistake is.
PS: When I don’t use the unified object but only a single object it works as intended but I want the prices to also stay in the cart. When I do this:
localStorage.setItem('myCart', JSON.stringify(this.state.cart))
instead of
const unified = Object.assign({}, {cart: this.state.cart}, {subtotal: this.state.cartSubTotal}, {tax: this.state.cartTax}, {total: this.state.cartTotal})
localStorage.setItem('myObject', JSON.stringify(unified))
it works as I said.
Code:
componentDidMount() {
this.setProducts();
this.setState({unified : !localStorage.getItem('myObject')
? {}
: JSON.parse(localStorage.getItem('myObject'))
})
};
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.addTotals();
const unified = Object.assign({}, {cart: this.state.cart}, {subtotal: this.state.cartSubTotal}, {tax: this.state.cartTax}, {total: this.state.cartTotal})
localStorage.setItem('myObject', JSON.stringify(unified))
});
};
Also, the three price amounts are set to zero in the local storage instead of the actual price.