Hi I got cat to work but need clarification on this or maybe even better way of doing things in the future.
So I have my cart
{
products: array(),
total_price: int()
}
cart is stored in cartContext and in localStorage.
Then I have all kind of methods to manipulate but there is one thing I don't get.
Delete from cart First method of creating new cart w/o clicked item
export const deleteFromCart = (existingCart, productDatabaseId) => {
let newProducts = existingCart.products.filter((obj) => {
return obj.databaseId !== productDatabaseId;
});
existingCart.products = newProducts;
existingCart = calculateTotalPrice(existingCart);
localStorage.setItem("cart", JSON.stringify(existingCart));
return existingCart;
};
Then handler
const [cart, setCart] = useContext(CartContext);
const handleDeleteFromCart = (databaseId) => {
let existingCart = localStorage.getItem("cart");
if (process.browser) {
existingCart = JSON.parse(existingCart);
let updatedCart = deleteFromCart(existingCart, databaseId);
setCart(updatedCart);
}
};
Questions:
- As you can see I'm creating whole new cart everytime when doing changes. I think it's clean solution as long as CartProvider is stateless with hooks. Am I right?
- I'm getting exisistingCart from local storage but I tried to use just state object for that manner
const [cart, setCart] = useContext(CartContext);
const handleDeleteFromCart = (databaseId) => {
if (process.browser) {
let existingCart = cart;
let updatedCart = deleteFromCart(existingCart, databaseId);
setCart(updatedCart);
}
};
In this case state won't refresh. setCart is setting previous version of the cart or not setting it at all. State doesn't change, only local storage cart is changing so after refresh (hook on loading cart from local storage) cart is proper(w/o clicked item) but it's not realtime. Why? My guess is that deleteFromCart method takes to loong to execute and setCart is executed before hand?
Need some clariffication on this.