in codelab-initial-state/public/js/homepage.js [98:131]
async listenForCart(uid) {
console.log(`listenForCart(${uid})`);
// If we were previously listening to the cart for
// a different user, unsubscribe.
if (this.cartItemsUnsub) {
this.cartItemsUnsub();
this.cartItemsUnsub = null;
}
// If needed, create the base cart object
const cartRef = this.db.collection("carts").doc(uid);
await cartRef.set(
{
ownerUID: uid
},
{ merge: true }
);
// Listen for updates to the cart
// TODO: Unsub from this as well
this.cartUnsub = cartRef.onSnapshot(cart => {
console.log("cart", cart.data());
const total = cart.data().totalPrice || 0;
const count = cart.data().itemCount || 0;
this.headerBar.setIconText("cart", `\$${total.toFixed(2)} (${count})`);
});
// Listen for updates to cart items
this.cartItemsUnsub = cartRef.collection("items").onSnapshot(items => {
this.setCartItems(items);
});
}