The cart grew one action at a time: addToCart (Building BookNest's Tab Bar), setQty (Checkout Form), clearCart (Handling Submission and Errors) and removeFromCart (Swipe to Remove). State holds only { id, qty } lines; the cart getter joins each to its book, and cartCount and cartTotal sum them, so a price change in books reaches the cart at once.
A cart that empties on every reload is a bug, so all four actions now go through one helper that assigns and saves the new array, and the state starts from what was saved:
const CART_KEY = 'booknest-cart';
const loadCart = () => {
try {
return JSON.parse(localStorage.getItem(CART_KEY)) || [];
} catch {
return []; // storage blocked or corrupt: start empty
}
};
const saveCart = (state, cart) => {
state.cart = cart; // assign a new array: only top-level assignments notify getters
localStorage.setItem(CART_KEY, JSON.stringify(cart));
};
...
cart: loadCart(), // [{ id, qty }]
...
addToCart({ state }, id) {
const line = state.cart.find((l) => l.id === id);
saveCart(state, line
? state.cart.map((l) => (l.id === id ? { ...l, qty: l.qty + 1 } : l))
: [...state.cart, { id, qty: 1 }]);
},After adding The Quiet Harbor and Gardens in Glass from their pages and reloading, the console showed:
console.log(localStorage.getItem('booknest-cart'), app.store.getters.cartCount.value);[{"id":1,"qty":1},{"id":6,"qty":1}] 2The badge read 2 and the Cart tab listed both books, $36.29 in all. No page knows about the storage, so Capacitor can move these two functions to Capacitor 243,123 's Preferences API: the operating system may reclaim a WebView's local storage when the device runs low on space.