trying to add an item in the Firestore collection after checking the condition that the item does not already exist.if it does exist increase the quantity of the item else add the new item with quantity 1.
function addToCart(item) {
console.log(item)
let cartItem = db.collection('cart-items').doc(item.id)
cartItem.get()
.then((doc) => {
if (doc.exists) {
cartItem.update({
quantity: doc.data().quantity + 1
})
}
else {
cartItem.set({
image: item.image,
make: item.make,
name: item.name,
rating: item.rating,
price: item.price,
quantity: 1
})
}
})
}
Doing a get-and-set like you're doing here can lead to a race condition if two users update the cart at the same time. You might think that won't happen in you use-case, but I'd still recommend guarding against it by using a transaction.
In this specific case though, it's much simpler and more idiomatic, so always perform a set operation and use the atomic increment operation to increase the quantity:
let cartItem = db.collection('cart-items').doc(item.id)
cartItem.set({
image: item.image,
make: item.make,
name: item.name,
rating: item.rating,
price: item.price,
quantity: firebase.firestore.FieldValue.increment(1)
})
It may feel wasteful to send the other field values multiple times, but you won't be charged more for the operation by Firestore here, and the code simplification is significant.